二叉树的最大深度,二叉树的最小深度,完全二叉树的节点个数

95 阅读1分钟

1. 二叉树的最大深度

二叉树深度和高度的区别如下图所示 image.png

//定义最大深度
int deep = 0;

public int maxDepth(TreeNode root) {
    getMaxDepth(root, 0);
    return deep;
}

void getMaxDepth(TreeNode tr, int tmp) {
    if (tr == null) {
        return;
    }
    //临时变量,用于确定deep的值
    tmp++;
    deep = deep < tmp ? tmp : deep;
    getMaxDepth(tr.left, tmp);
    getMaxDepth(tr.right, tmp);
    tmp--;
}

2. 二叉树的最小深度

public int minDepth(TreeNode root) {
   if (root == null) {
       return 0;
   }
   //求最小深度,其实和求最小高度是一样的,用求最小高度的方式来理解此题会更好。
   int leftMinHeight = minDepth(root.left);
   int rightMinHeight = minDepth(root.right);
   if (root.left == null) {
       return rightMinHeight + 1;
   }
   if (root.right == null) {
       return leftMinHeight + 1;
   }

   return Math.min(leftMinHeight, rightMinHeight) + 1;
}

3. 完全二叉树的节点个数

//后序递归遍历
public int countNodes01(TreeNode root) {
    if (root == null) {
        return 0;
    }
    int leftNum = countNodes01(root.left);
    int rightNum = countNodes01(root.right);
    return leftNum + rightNum + 1;
}

//优化方案,利用完全二叉树的特性:完全二叉树的子树都是满二叉树
public int countNodes02(TreeNode root) {
    if (root == null) {
        return 0;
    }
    int leftDeep = 0, rightDeep = 0;
    TreeNode leftNode = root.left;
    TreeNode rightNode = root.right;
    //计算左子树深度
    while (leftNode != null) {
        leftNode = leftNode.left;
        leftDeep++;
    }
    //计算右子树深度
    while (rightNode != null) {
        rightNode = rightNode.right;
        rightDeep++;
    }
    //若深度相同,说明此root是一棵满二叉树,进行计算并返回
    if (leftDeep == rightDeep) {
        return (2 << leftDeep) - 1;
    }
    //若root不是满二叉树,则进行以下逻辑
    int leftNum = 0, rightNum = 0;
    leftNum = countNodes02(root.left);
    rightNum = countNodes02(root.right);
    return leftNum + rightNum + 1;
}