深度指的是 根节点 -> 叶子节点 的距离
高度指的是 叶子节点 -> 根节点 的距离
1. 二叉树的最大深度
后序遍历,左右中,求得其实是高度,因为后序遍历是先求出子节点的高度,再加一
对于同一个叶子节点,它的高度和根节点到它的深度是相等的
所有一个树的最大高度等于最大深度
class Solution {
//深度:从上到下,后序,左右中
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int leftHight = maxDepth(root.left);
int rightHight = maxDepth(root.right);
return 1 + (leftHight > rightHight ? leftHight : rightHight);
}
}
2. 二叉树的最小深度
需要注意的是
要判断根节点的左右子树的高度
如果为0,说明没有左右子节点
自然在这边就没有深度这一说,需要舍弃这一边的值
class Solution {
public int minDepth(TreeNode root) {
//深度:从上到下,后序,左右中
if(root == null) return 0;
int leftHight = minDepth(root.left);
int rightHight = minDepth(root.right);
if(leftHight == 0) return rightHight + 1;
if(rightHight == 0) return leftHight + 1;
return 1 + (leftHight < rightHight ? leftHight : rightHight);
}
}
3. 完全二叉树的节点个数
222. 完全二叉树的节点个数 - 力扣(LeetCode)
可以用递归实现前中后序遍历每一个子节点,计数就行
class Solution {
public int res;
public int countNodes(TreeNode root) {
preorder(root);
return res;
}
public void preorder(TreeNode root){
if(root == null) return;
res++;
preorder(root.left);
//res++;
preorder(root.right);
//res++;
}
}
当然,可以更简单一点实现
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int leftCount = countNodes(root.left);
int rightCount = countNodes(root.right);
return leftCount+rightCount+1;
}
}
- 时间复杂度:O(n)
满二叉树:最底层在同一层,且最底层填满。
满二叉树的结点数为:2^depth - 1
完全二叉树:除了最底层,其余层填满,并且最底层从最左连续。
完全二叉树的左右子树中一定存在一个满二叉树
利用满二叉树特性
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
TreeNode left = root.left;
TreeNode right = root.right;
int leftDepth = 1, rightDepth = 1; //leftDepth初始为1
while (left != null) { // 求左子树深度
left = left.left;
leftDepth++;
}
while (right != null) { // 求右子树深度
right = right.right;
rightDepth++;
}
//是满二叉树,直接公式求节点数量,返回
if (leftDepth == rightDepth) {
return (1 << leftDepth) - 1; // (1<<n) 相当于2^n
}
//不是满二叉树,递归寻找子树的满二叉树,结果求和再加上自己
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
- 时间复杂度:O(log n × log n)
左右指针从某一个子节点一直沿最外侧向下,直到null(子树节点数量为0),并记录深度
若左右深度相等,则说明以该子节点为根节点的树为满二叉树,直接用公式求得该树节点数量并返回值
若不相等,则从该节点继续判断它的左右子树是否为满二叉树,递归向下,并将左右子树的节点数量相加再加1,然后返回值给上一层