本题源自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: 非递归
用俩个栈 来保存访问 路径
代码;
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
stack<string> str;
stack<TreeNode*> tree;
if(root==NULL)
return res;
tree.push(root);
str.push(to_string(root->val));
while(!tree.empty()){
TreeNode* p=tree.top();
tree.pop();
string s=str.top();
str.pop();
if(!p->left && !p->right){
res.push_back(s);
continue;
}
if(p->left){
tree.push(p->left);
str.push(s+"->"+to_string(p->left->val));
}
if(p->right){
tree.push(p->right);
str.push(s+"->"+to_string(p->right->val));
}
}
return res;
}