1.问题描述:给一棵二叉树,找出从根节点到叶子节点的所有路径。
2.思路:正如样例
给出下面这棵二叉树:
1
/ \
2 3
\
5
所有根到叶子的路径为:
[
"1->2->5",
"1->3"
]
如果左子树右子树都为空则把根节点储存在向量中,然而如果左子树不为空则对左子树调用递归函数,如果右子树不为空则对右子树调用递归函数,最后返回向量v即可。
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> v;
if(root==NULL) return v;
binaryTree(root,v,to_string(root->val));
return v;
}
void binaryTree(TreeNode *root,vector<string>&ve,string s)
{ if(root->left==NULL&&root->right==NULL)
{ ve.push_back(s); return;}
if(root->left!=NULL)
binaryTree(root->left,ve,s+"->"+to_string(root->left->val));
if(root->right!=NULL)
binaryTree(root->right,ve,s+"->"+to_string(root->right->val));
}
4.感想:这个题目里面学到的新的知识就是to_string是将某一类型转化为string类型。