Skip to content

257. Binary Tree Paths

https://leetcode.com/problems/binary-tree-paths/

js
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {string[]}
 */
var binaryTreePaths = function(root) {
    const paths = []
    traversePaths(root, [], paths)
    return paths.map(path => path.join('->'))
};

function traversePaths(root, path, paths) {
    if (!root) {
        return
    }
    if (!root.left && !root.right) {
        paths.push([...path, root.val])
    }
    if (root.left) {
        traversePaths(root.left, [...path, root.val], paths)
    }
    if (root.right) {
        traversePaths(root.right, [...path, root.val], paths)
    }
}
py
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution(object):

    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        paths = []
        self.traversePaths(root, [], paths)
        return ['->'.join(path) for path in paths]

    def traversePaths(self, root, path, paths):
        if not root:
            return
        if not root.left and not root.right:
            paths.append([*path, str(root.val)])
        if root.left:
            self.traversePaths(root.left, [*path, str(root.val)], paths)
        if root.right:
            self.traversePaths(root.right, [*path, str(root.val)], paths)