[#C] 257 Binary Tree Paths - LeetCode
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
思路:通过递归叠加每个节点
/**
* 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) return res;
if (root.left == null && root.right == null) {
res.add(String.valueOf(root.val));
return res;
}
List<String> lefts = binaryTreePaths(root.left);
for (int i = 0; i < lefts.size(); i++) {
res.add(root.val + "->" + lefts.get(i));
}
List<String> rights = binaryTreePaths(root.right);
for (int i = 0; i < rights.size(); i++) {
res.add(root.val + "->" + rights.get(i));
}
return res;
}
}
/**
* 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 == NULL) return res;
if (root->left == NULL && root->right == NULL) {
res.push_back(to_string(root->val));
return res;
}
vector<string> lefts = binaryTreePaths(root->left);
for (int i = 0; i < lefts.size(); i++) {
res.push_back(to_string(root->val) + "->" + lefts[i]);
}
vector<string> rights = binaryTreePaths(root->right);
for (int i = 0; i < rights.size(); i++) {
res.push_back(to_string(root->val) + "->" + rights[i]);
}
return res;
}
};