问题描述:
给一颗二叉树,找出从根节点到叶子节点的所有路径。
实现思路:
利用递归找出所有路径,保存每一个节点之前的路径。找到对每一条路径中各个节点的值作为一个字符串加入vector(1)中,然后将该vector(2)中的各个值输出复制给string型变量a,然后把a加入另一个储存所有路径的vector(2)中,最后返回该vector;要注意当把a加入到vector(2)之后,要再把a清空。
代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
vector<string> vv;
string a;
void findpath(TreeNode *root,vector<string> &path) {
if(root==NULL) return;
if(root!=NULL) {
path.push_back(to_string(root->val));
if(root->left==NULL&&root->right==NULL) {
for( vector<string>::iterator it=path.begin();it!=path.end();it++) {
if(it==path.begin()) a=path[0];
else {
a=a+"->"+*it;
}
}
vv.push_back(a);
a="";
}
findpath(root->left,path);
findpath(root->right,path);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> path;
// Write your code here
if(root!=NULL) {
findpath(root,path);
}
return vv;
}
};
感想:
path要用做全局变量,要引用。对每一条路径a加进路径的vector之后,要把a清空,开始记录下一条路径。最后返回路径的vector。对于利用递归找路径时,要注意删除最后一个节点的值,保存上一节点以前的路径。