/** * 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} */ const sumNumbers = function (root) { }; /* 思路:利用DFS来遍历每一个节点,直到遍历到叶子节点,把从root节点到叶子节点代表的数字求出了,之后求和,处理完所有的叶子节点 那么sum就是我们要返回的最终结果,叶子节点要想知道从root节点到父节点所代表的数字,就必须用一个numStack的栈储存。 */ function f1(root) { let sum = 0; // 根节点到叶子节点代表的数字之和 const nodeStack = [root]; // 遍历每一个节点 const numStack = [root.val]; // 每一个节点所表示的数字 // DFS遍历所有节点 while (nodeStack.length > 0) { // 弹出要处理的节点,和root节点到这个节点表示的数字 const node = nodeStack.pop(); const nodeNum = numStack.pop(); // 如果当前节点是叶子节点将他与sum求和 if (!node.left && !node.right) { sum += nodeNum; continue; } // 如果当前节点的左右子节点存在,将它和它表示的num压入栈中,后续处理 if (node.right) { nodeStack.push(node.right); numStack.push(nodeNum * 10 + node.right.val); } if (node.left) { nodeStack.push(node.left); numStack.push(nodeNum * 10 + node.left.val); } } // 返回结果 return sum; } /* 这个题目利用BFS也能解决,只需改一下f1就行,把栈改成队列 */ function f2(root) { let sum = 0; // 根节点到叶子节点代表的数字之和 const nodeQue = [root]; // 遍历每一个节点 const numQue = [root.val]; // 每一个节点所表示的数字 // DFS遍历所有节点 while (nodeQue.length > 0) { // 弹出要处理的节点,和root节点到这个节点表示的数字 const node = nodeQue.shift(); const nodeNum = numQue.shift(); // 如果当前节点是叶子节点将他与sum求和 if (!node.left && !node.right) { sum += nodeNum; continue; } // 如果当前节点的左右子节点存在,将它和它表示的num压入栈中,后续处理 if (node.right) { nodeQue.push(node.right); numQue.push(nodeNum * 10 + node.right.val); } if (node.left) { nodeQue.push(node.left); numQue.push(nodeNum * 10 + node.left.val); } } // 返回结果 return sum; } /* 利用dfs递归,递归函数接收两个参数一个参数为node,表示当前的节点,一个参数为prevNum,表示根节点到父节点表示的数字,返回值 表示的是这个根节点到这个节点下面任意字节的表示的数字的总和 */ const dfs = (root, prevNum) => { if (root === null) { return 0; } const sum = prevNum * 10 + root.val; if (root.left == null && root.right == null) { return sum; } // 将所有叶子节点的值求和 return dfs(root.left, sum) + dfs(root.right, sum); }; const f3 = function (root) { return dfs(root, 0); }; // 上面的递归函数就做了两件事情,找叶子节点,找到,将他与父节点表示的数字组合成新的数字,最后求和