来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sum-of-root-to-leaf-binary-numbers 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。
例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。 对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。
返回这些数字之和。题目数据保证答案是一个 32 位 整数。
解答
只是个前序遍历,但要注意最叶子节点可能会执行两次,因为最叶子节点没有 left 和 right,如果放入 sumRootToLeafByPath,就会执行两次 null
/*** 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;function sumRootToLeafByPath (node, path) {if (!node) return null;path += node.val;node.left && sumRootToLeafByPath(node.left, path);node.right && sumRootToLeafByPath(node.right, path);if (!node.left && !node.right) {return sum += Number('0b' + path);}}sumRootToLeafByPath(root, '');return sum;};
