LeetCode Binary Tree Paths
2018-04-17 本文已影响0人
codingcyx
Given a binary tree, return all root-to-leaf paths.
完美解法:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if(!root) return res;
helper(root, res, to_string(root -> val));
return res;
}
void helper(TreeNode* root, vector<string>& res, string st) {
if(root -> left == root -> right) {
res.push_back(st);
return ;
}
if(root -> left) helper(root -> left, res, st + "->" + to_string(root -> left -> val));
if(root -> right) helper(root -> right, res, st + "->" + to_string(root -> right -> val));
}
传参中传递一个st,到达叶子结点时可以直接压入结果,而如果像下面的解法,就很不优美了(叶子节点处理逻辑复杂)。
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
vector<string> res;
if(!root) return res;
dfs(root, path, res);
return res;
}
void dfs(TreeNode* root, vector<int>& path, vector<string>& res) {
if(root -> left == root -> right){
string tmp;
path.push_back(root -> val);
for(int i = 0; i<path.size() - 1; i++)
tmp += to_string(path[i]) + "->";
tmp += to_string(path[path.size()-1]);
res.push_back(tmp);
path.pop_back();
return;
}
path.push_back(root -> val);
if(root -> left) dfs(root -> left, path, res);
if(root -> right) dfs(root -> right, path, res);
path.pop_back();
}