您的位置:首页 > 其它

Leetcode算法学习日志-257 Binary Tree Paths

2017-12-20 11:55 453 查看

Leetcode 257 Binary Tree Paths

题目原文

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

1
/   \
2     3
\
5

All root-to-leaf paths are:

["1->2->5", "1->3"]

题意分析

输出所有路径。

解法分析

本题采用深度优先搜索,需要注意返回条件,必须要左右子树都空时才返回。C++代码如下:

class Solution {
public:
void dfs(TreeNode* root,string &path,vector<string> &res){
string k=to_string(root->val);
path+=k;
path+="->";
if((root->right==NULL)&&(root->left==NULL)){
path.erase(path.begin()+path.size()-2,path.end());
res.push_back(path);
path.erase(path.begin()+path.size()-k.size(),path.end());
return;
}
if(root->left!=NULL)
dfs(root->left,path,res);
if(root->right!=NULL)
dfs(root->right,path,res);
path.erase(path.begin()+path.size()-k.size()-2,path.end());
}
vector<string> binaryTreePaths(TreeNode* root) {
string path;
vector<string> res;
if(root==NULL)
return res;
dfs(root,path,res);
return res;
}
};上述代码中需要注意path是一个string,而val都是int,需要进行转化。同时path最好不要作为引用输入,这样会造成恢复path过于麻烦,直接将其作为形参可以避免恢复的麻烦。修改后的代码如下:
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (root == NULL) return res;

backtrack(root,"",res);
return res;
}
void backtrack(TreeNode* root, string s, vector<string>& res){
if (!root) return;
if (!root->left && !root->right) {
s += to_string(root->val);
res.push_back(s);
return ;
}

backtrack(root->left, s+to_string(root->val)+"->", res);
backtrack(root->right, s+to_string(root->val)+"->", res);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: