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”]
这道题是利用DFS算法的思路。先从root出发,然后递归左子树,再递归右子树。注意这里to_string函数用于将int型转化为string型
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string>v;
vector<string> binaryTreePaths(TreeNode* root) {
if(!root)return v;
helper(root,to_string(root->val));
return v;
}
void helper(TreeNode* root,string t){
if(!root->left&&!root->right){
v.push_back(t);
return;
}
if(root->left){
helper(root->left,t+"->"+to_string(root->left->val));
}
if(root->right){
helper(root->right,t+"->"+to_string(root->right->val));
}
}
};