LeetCode-257. Binary Tree Pathshttps://leetcode.com/problems/binary-tree-paths/
题目描述
Given the root
of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
Example 1:
Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"]
Example 2:
Input: root = [1] Output: ["1"]
Constraints:
- The number of nodes in the tree is in the range
[1, 100]
. -100 <= Node.val <= 100
解题思路
【C++】
/**
* 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> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (root) helper(root, "", res);
return res;
}
void helper(TreeNode* root, string out, vector<string>& res) {
if (!root->left && !root->right) res.push_back(out + to_string(root->val));
if (root->left) helper(root->left,out + to_string(root->val) + "->", res);
if (root->right) helper(root->right,out + to_string(root->val) + "->", res);
}
};
【Java】
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root != null) {dfs(root, "", res);}
return res;
}
void dfs(TreeNode root, String out, List<String> res) {
if (root.left == null && root.right == null) {res.add(out + root.val);}
if (root.left != null) {dfs(root.left, out + root.val + "->", res);}
if (root.right != null) {dfs(root.right, out + root.val + "->", res);}
}
}
参考文献