Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

1022. Sum of Root To Leaf Binary Numbers #320

Open Tcdian opened 3 years ago

Tcdian commented 3 years ago

1022. Sum of Root To Leaf Binary Numbers

给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。

对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。

以 10^9 + 7 为模,返回这些数字之和。

Example

Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

Note

Tcdian commented 3 years ago

Solution

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumRootToLeaf = function(root) {
    let sum = 0;
    const path = [];
    dfs(root);
    return sum;

    function dfs(root) {
        if (root === null) {
            return;
        }
        path.push(root.val);
        if (root.left === null && root.right === null) {
            sum += parseInt(path.join(''), 2);
        }
        dfs(root.left);
        dfs(root.right);
        path.pop();
    }
};
/**
 * Definition for a binary tree node.
 * 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)
 *     }
 * }
 */

function sumRootToLeaf(root: TreeNode | null): number {
    let sum = 0;
    const path: number[] = [];
    dfs(root);
    return sum;

    function dfs(root: TreeNode | null) {
        if (root === null) {
            return;
        }
        path.push(root.val);
        if (root.left === null && root.right === null) {
            sum += parseInt(path.join(''), 2);
        }
        dfs(root.left);
        dfs(root.right);
        path.pop();
    }
};