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"]
又是较为常见的BST的遍历,我还是用比较习惯的递归解法:
/**
* 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> binaryTreePaths(TreeNode* root) {
vector<string> ans;
string path;
TreePaths(root,path,ans);
return ans;
}
void TreePaths(TreeNode* root,string path,vector<string> &ans){
if(root==nullptr) return ;
if(!path.empty()){
path=path+"->";
}
path=path+to_string(root->val);
if(root->left==nullptr&&root->right==nullptr) {
ans.push_back(path);
return ;
}else {
if(root->left) { TreePaths(root->left,path,ans);}
if(root->right) { TreePaths(root->right,path,ans);}
}
}
};