给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: [“1->2->5”, “1->3”]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
解题思路:
这是最简单的深度优先算法类型的题目了,思路就是深度优先遍历root,向左或者向右,一直到左右为null的时候结束,这个时候就可以把路径放到vector后面了,代码如下:
/**
* 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;
}
dfs(res, root, "");
return res;
}
void dfs(vector<string>& res, TreeNode* root, string path){
path += to_string(root->val);
if(root->left == NULL && root->right == NULL){
res.push_back(path);
return;
}
if(root->left)dfs(res, root->left, path + "->");
if(root->right)dfs(res, root->right, path + "->");
}
};