给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
/**
* 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> result;
vector<string> binaryTreePaths(TreeNode* root) {
string path; //在这里,我们定义一个中间变量来保存结果
dfs(root,path);//利用DFS
return result;//返回结果
}
void dfs (TreeNode* root,string path){
if(!root) return; // 如果为空的话,直接返回
if(path.size()) path +="->"; // 如果不是根节点的话,我们 要首先加上 "->"
path +=to_string(root->val); // 把数据保存起来, path 里面存储着从根节点到当前节点的路径
if (!root->left && !root->right) result.push_back(path); // 只有当这个节点为根节点的时候我们才会把数据保存起来
else {
dfs(root->left,path); // 否则的话,遍历一下左子节点
dfs(root->right,path);// 遍历一下右子节点
}
}
};
// 加油,加油。 Try to make yourself more excellent...