104.二叉树的最大深度
111.二叉树的最小深度
222.完全二叉树的节点个数
104. 二叉树的最大深度
var maxDepth = function(root) {
if (!root) return 0;
let res = 0;
const q = [];
q.push(root);
while (q.length > 0) {
let len = q.length;
while (len--) {
const node = q.shift();
if (node.right) q.push(node.right);
if (node.left) q.push(node.left);
}
res += 1;
}
return res;
};
var maxDepth = function(root) {
if (!root) return 0;
const dL = maxDepth(root.left);
const dR = maxDepth(root.right);
return Math.max(dL, dR) + 1;
};
111. 二叉树的最小深度
- 我思路误区:找错了终止条件,左右子节点均不存在的情况包含在了最后一个
else里
- 关键字:叶子节点 —— 最小深度是从根节点到最近叶子节点的最短路径
var minDepth = function(root) {
if (!root) return 0;
if (!root.left && root.right) {
return minDepth(root.right) + 1;
} else if (root.left && !root.right) {
return minDepth(root.left) + 1;
} else {
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
};
222. 完全二叉树的节点个数
- 感想:想到了连续求左和右节点的长度,但没能想到 完全二叉树=二者相同 && 二者不同时分别求其数量+1(完全二叉树和满二叉树的关系)
var countNodes = function(root) {
if (!root) return 0;
let dL = 1, dR = 1;
let left = root.left;
let right = root.right;
while (left) {
left = left.left;
dL += 1;
}
while (right) {
right = right.right;
dR += 1;
}
if (dR === dL) {
return 2 ** dL - 1;
}
return countNodes(root.left) + countNodes(root.right) + 1;
};