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

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

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

/*class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param root TreeNode类
 * @param target int整型
 * @return int整型二维数组
 */

export function FindPath(root: TreeNode, target: number): number[][] {
    const resultPath: any = [];
    let temp: number[] = [];
    // write code here
    function path(root: TreeNode, sum: number) {
        if (!root) return;
        temp.push(root.val);
        sum -= root.val
        if (root.left == null && root.right == null && sum == 0) {
            resultPath.push(temp.slice(0));
        }
        path(root.left, sum);
        path(root.right, sum);
        temp.pop();
    }
    path(root,target)
    return resultPath;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务