题解 | #二叉树中和为某一值的路径(二)#

二叉树中和为某一值的路径(二)

https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function FindPath(root, expectNumber)
{
    // write code here
    let paths = []
    if (!root) return paths

    const restNumber = expectNumber - root.val
    if (restNumber === 0) {
        if (root.left === null || root.right === null) {
            paths = [[root.val]]
        } else {
            paths = []
        }
    } else {
        const leftPaths = FindPath(root.left, restNumber)
        const rightPaths = FindPath(root.right, restNumber)
        const rootPaths = leftPaths.concat(rightPaths)
        paths = rootPaths.map((path) => [root.val].concat(path))
    }
    return paths
}
module.exports = {
    FindPath : FindPath
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务