本题源自leetcode
--------------------------------------------------
思路1 递归:
先访问根节点。然后递归遍历左子树和右子树。遇到叶节点则保存路径。
代码
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if(root==NULL)
return res;
findPath(root,res,to_string(root->val));
return res;
}
void findPath(TreeNode* root,vector<string>& res,string s){
if(!root->left && !root->right){
res.push_back(s);
return;
}
if(root->left){
findPath(root->left,res,s+"->"+to_string(root->left->val));
}
if(root->right){
findPath(root->right,res,s+"->"+to_string(root->right->val));
}
}
思路2: 非递归
用俩个栈 来保存访问 路径
代码;
<