一.题目描述
给一棵二叉树,找出从根节点到叶子节点的所有路径。
样例
给出下面这棵二叉树:
1
/ \
2 3
\
5
所有根到叶子的路径为:
[
"1->2->5",
"1->3"
]
二.解题思路
给出下面这棵二叉树:
1
/ \
2 3
\
5
所有根到叶子的路径为:
[
"1->2->5",
"1->3"
]
当一个节点的左右子树都为空时,把从根节点到该节点的路径保存在向量中,找到所有的叶子节点就完成了对所有路径的保存.
三.实现代码
/**
* 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> binaryTreePaths(TreeNode* root) {
// Write your code here
vector<string>Paths;
if(root==NULL) return Paths;
ff(root,Paths,to_string(root->val) );
return Paths;
}
void ff(TreeNode *root,vector<string>&Paths,string strPaths){
if(root->left==NULL&&root->right==NULL){
Paths.push_back(strPaths);
return;
}
if(root->left!=NULL)
ff(root->left,Paths,strPaths+"->"+to_string(root->left->val) );
if(root->right!=NULL)
ff(root->right,Paths,strPaths+"->"+to_string(root->right->val) );
}
};
四.感悟
/**
* 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> binaryTreePaths(TreeNode* root) {
// Write your code here
vector<string>Paths;
if(root==NULL) return Paths;
ff(root,Paths,to_string(root->val) );
return Paths;
}
void ff(TreeNode *root,vector<string>&Paths,string strPaths){
if(root->left==NULL&&root->right==NULL){
Paths.push_back(strPaths);
return;
}
if(root->left!=NULL)
ff(root->left,Paths,strPaths+"->"+to_string(root->left->val) );
if(root->right!=NULL)
ff(root->right,Paths,strPaths+"->"+to_string(root->right->val) );
}
};
将一个int类型转化为string类型可用to_string().