来源:力扣(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

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val, left, right) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.left = (left===undefined ? null : left)
  6. * this.right = (right===undefined ? null : right)
  7. * }
  8. */
  9. /**
  10. * @param {TreeNode} root
  11. * @return {number}
  12. */
  13. var sumRootToLeaf = function(root) {
  14. let sum = 0;
  15. function sumRootToLeafByPath (node, path) {
  16. if (!node) return null;
  17. path += node.val;
  18. node.left && sumRootToLeafByPath(node.left, path);
  19. node.right && sumRootToLeafByPath(node.right, path);
  20. if (!node.left && !node.right) {
  21. return sum += Number('0b' + path);
  22. }
  23. }
  24. sumRootToLeafByPath(root, '');
  25. return sum;
  26. };