二叉树的所有路径
给一棵二叉树,找出从根节点到叶子节点的所有路径。
样例
给出下面这棵二叉树:
1
/ \
2 3
\
5
所有根到叶子的路径为:
[
"1->2->5",
"1->3"
]
解题思路:dfs进行遍历每次向vector里面保存一个节点,当判断是叶子节点时调用函数f将int类vector转化为string类数组并加入vector里面,最终返回string的vector即可,关键是在每步还原现场才能将所有路径进行保存。
#include<sstream>
class Solution {
public:
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
vector<int>tem;
vector<string>Ans;
void F(vector<int>x){
stringstream sout;
sout<<x[0];
string ans;
ans=ans+sout.str();
for(int i=1;i<x.size();i++){
stringstream Sout;
Sout<<x[i];
ans+="->";
ans+=Sout.str();
}
Ans.push_back(ans);
}
vector<string> binaryTreePaths(TreeNode* root) {
// Write your code here
if(root==NULL)return Ans;
tem.push_back(root->val);
if(root->left!=NULL)binaryTreePaths(root->left);
if(root->right!=NULL)binaryTreePaths(root->right);
if(root->left==NULL&&root->right==NULL){
F(tem);
}
tem.erase(tem.begin()+tem.size()-1);
return Ans;
}
};