首发于 语雀文档@blueju
代码:
/*** 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) {if (root === null) return 0const pathList = []const dfs = (root, pathString) => {if (root === null)returnif (root.left === null && root.right === null) {pathList.push(pathString + root.val)return}dfs(root.left, pathString + root.val)dfs(root.right, pathString + root.val)}dfs(root, '')return pathList.reduce((prev, curr) => {return prev + parseInt(curr, 2)}, 0)};
