目录
难度 简单
给你一个二叉树的根节点 root
,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3,null,5] 输出:["1->2->5","1->3"]
示例 2:
输入:root = [1] 输出:["1"]
提示:
[1, 100]
内-100 <= Node.val <= 100
- /**
- * 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
binaryTreePaths(TreeNode* root) { -
- }
- };
思路就是遍历到叶子结点就push当前路径, 到最后剪枝,不用写函数出口。
- /**
- * 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 {
- vector
ret; - public:
- vector
binaryTreePaths(TreeNode* root) { - dfs(root, "");
- return ret;
- }
-
- void dfs(TreeNode* root, string path)
- {
- path += to_string(root->val); // 不可能传空root进来
- if(root->left == nullptr && root->right == nullptr)
- {
- ret.push_back(path); // 是叶子结点就push当前路径
- }
- else // 不是叶子结点就先加上箭头
- {
- path += "->";
- }
- if(root->left != nullptr) // 剪枝,此时不用写函数出口
- dfs(root->left, path);
- if(root->right != nullptr)
- dfs(root->right, path);
- }
- };