algorighm/top-interview-leetcode150/binary-tree/129求根节点到叶子节点数字之和.js

111 lines
3.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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);
};
// 上面的递归函数就做了两件事情,找叶子节点,找到,将他与父节点表示的数字组合成新的数字,最后求和