8. 二叉树的最大深度
二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
而根节点的高度就是二叉树的最大深度
- 递归法
- 确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int类型。
- 确定终止条件:如果为空节点的话,就返回0,表示高度为0。
- 确定单层递归的逻辑:先求它的左子树的深度,再求右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。
var maxDepth = function(root) {
if(root === null) { //终止条件为节点为空
return 0; //返回值为number
}
let left = maxDepth(root.left); //递归返回左子树的深度
let right = maxDepth(root.right); //递归返回右子树的深度
return Math.max(left, right) + 1; //深度需要+1,因为要算上当前节点的深度
};
这种难以理解的递归逻辑可以干脆不理解,直接按照手感知道left和right会返回左右子树的最大深度就行了。
而且递归的理解也在于理解回溯。
- 前序遍历递归(好理解)
var maxDepth = function(root) {
let result = 0;
if(root === null) {
return 0;
}
const getDepth = function(root, depth) { //js中递归调用函数还需要使用函数内的变量result时,用函数表达式定义要递归的函数
result = Math.max(result, depth); //中
if(root.left === null && root.right === null) { //终止条件也可以是root===null,因为下边还要判断啊,太蠢了还思考了哎呦喂
return; //递归终止条件
}
if(root.left) { //左
depth++;
getDepth(root.left, depth);
depth--; // 回溯一层,depth需要减一
}
if(root.right) { //右
depth++;
getDepth(root.right, depth);
depth--; // 回溯一层,depth需要减一
}
return;
}
getDepth(root, 1);
return result;
};
- 层序遍历法
9. 二叉树的最小深度
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
- 递归法
var minDepth = function(root) {
if(root === null) {
return 0;
}
let leftDepth = minDepth(root.left); //返回左子树的最小深度
let rightDepth = minDepth(root.right);
//回溯出来时的判断
if(root.left === null && root.right !== null) { //说明当前根节点不是叶子结点,则最小深度在右子树的某个叶子结点上
return rightDepth + 1;
}
if(root.left === null && root.right !== null) { //说明当前根节点不是叶子结点,则最小深度在左子树的某个叶子结点上
return leftDepth + 1;
}
let result = 1 + Math.min(leftDepth, rightDepth);
return result;
};
- 前序遍历递归
var minDepth = function(root) {
let result = Number.MAX_VALUE;
if(root === null) {
return 0;
};
const getDepth = function(root, depth) {
if(root === null) {
return 0;
}
// 中
if(root.left === null && root.right === null) { //判断已经到了叶子结点,可以进行处理
result = Math.min(result, depth);
}
if(root.left) {
depth++;
getDepth(root.left, depth);
depth--;
}
if(root.right) {
depth++;
getDepth(root.right, depth);
depth--;
}
return;
}
getDepth(root, 1);
return result;
};
- 层序遍历法
10. 完全二叉树的节点个数
- 递归法
var countNodes = function(root) {
if(!root) {
return 0;
}
let leftCount = countNodes(root.left);
let rightCount = countNodes(root.right);
return leftCount + rightCount + 1;
};
- 利用完全二叉树特点的求法