JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

Code

/**
 * 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;

        helper(res, root, "");
        return res;
    }

    private void helper(List<String> res, TreeNode root, String curr) {
        if(root == null) return;
        if(root.left == null && root.right == null) {
            res.add(curr + root.val);
            return;
        }

        helper(res, root.left, curr + root.val + "->");
        helper(res, root.right, curr + root.val + "->");
    }
}
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def helper(self, res: List[str], root: TreeNode, curr: str):
        if not root:
            return
        if not root.left and not root.right:
            res.append(curr + str(root.val))
            return

        if root.left:
            self.helper(res, root.left, curr + str(root.val) + "->")

        if root.right:
            self.helper(res, root.right, curr + str(root.val) + "->")

    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        res = []
        self.helper(res, root, "")
        return res