题目描述:
给你一个二叉树的根节点 root
,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3,null,5] 输出:["1->2->5","1->3"]
示例 2:
输入:root = [1] 输出:["1"]
提示:
- 树中节点的数目在范围
[1, 100]
内 -100 <= Node.val <= 100
题目链接:
解题主要思路:
典型的dfs深度优先遍历,涉及到回溯,在递归回溯的过程中,我们可以借助临时变量传参的设计来记录上一层节点的路径。
解题代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> ret; // 储存结果
vector<string> binaryTreePaths(TreeNode* root) {
dfs(root, "");
return ret;
}
void dfs(TreeNode* root, string path)
{
string new_path = path + to_string(root->val);
// 判断是否为叶子结点,如果是则将路径输入到ret中
if (root->left == nullptr && root->right == nullptr) {
ret.push_back(new_path);
return;
}
// dfs
new_path += "->";
if (root->left) dfs(root->left, new_path);
if (root->right) dfs(root->right, new_path);
}
};