首发于 语雀文档@blueju

    代码:

    1. /**
    2. * Definition for a binary tree node.
    3. * class TreeNode {
    4. * val: number
    5. * left: TreeNode | null
    6. * right: TreeNode | null
    7. * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
    8. * this.val = (val===undefined ? 0 : val)
    9. * this.left = (left===undefined ? null : left)
    10. * this.right = (right===undefined ? null : right)
    11. * }
    12. * }
    13. */
    14. function sumRootToLeaf(root) {
    15. if (root === null) return 0
    16. const pathList = []
    17. const dfs = (root, pathString) => {
    18. if (root === null)
    19. return
    20. if (root.left === null && root.right === null) {
    21. pathList.push(pathString + root.val)
    22. return
    23. }
    24. dfs(root.left, pathString + root.val)
    25. dfs(root.right, pathString + root.val)
    26. }
    27. dfs(root, '')
    28. return pathList.reduce((prev, curr) => {
    29. return prev + parseInt(curr, 2)
    30. }, 0)
    31. };