问题:
https://leetcode.com/problems/binary-tree-paths/?tab=Description
Given a binary tree, return all root-to-leaf paths.
给定一棵树,找出所有从根到叶子节点的路径
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are: [“1->2->5”, “1->3”]
分析:
树的深度优先遍历。使用递归的方法来进行求解的,从根节点开始,若左子树不为空,则遍历左子树,若左子树的左孩子不为空,则遍历左孩子,否则遍历右孩子…..直到遍历完最后一个叶子节点为止。
参考C++代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if(root==NULL) return res;
if(root->left==NULL&&root->right==NULL){
res.push_back(to_string(root->val));
return res;
}
if(root->left!=NULL)
res=binaryTreePaths(root->left);
if(root->right!=NULL){
vector<string> tem;
tem=binaryTreePaths(root->right);
for(int i=0;i<tem.size();i++){
res.push_back(tem[i]);
}
}
for(int i=0;i<res.size();i++){
res[i]=to_string(root->val)+"->"+res[i];
}
return res;
}
};