一、运行结果
二、题目
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3,null,5]
输出:["1->2->5","1->3"]
示例 2:
输入:root = [1]
输出:["1"]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-paths
三、思路
从跟节点到一个叶子节点经过的所有节点构成一条路径,可以使用递归的深度优先遍历算法,每遇到一个叶子节点就将路径保存到结果数组中。
四、代码
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
if(root == NULL) return ans;
string path = "";
dfs(root, ans, path);
return ans;
}
// 递归深度优先搜索
void dfs(TreeNode* root, vector<string>& res, string path){
if(root->left == NULL && root->right == NULL){ //叶子结点
path += to_string(root->val);
res.push_back(path);
return;
}
path += to_string(root->val);
path += "->";
if(root->left){ //递归遍历左子树
dfs(root->left, res, path);
}
if(root->right){ //递归遍历右子树
dfs(root->right, res, path);
}
}
};