二叉树的最大深度和最小深度

转载:https://blog.csdn.net/xiongqiaochu/article/details/70313031

二叉树的定义:

struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

二叉树的最大深度

给定一个二叉树,找出其最大深度。 
二叉树的深度为根节点到最远叶子节点的距离。

如果二叉树为空,则深度为0 
如果不为空,分别求左子树的深度和右子树的深度,取最大的再加1。

int maxDepth(TreeNode *root) {
        if(root == nullptr)
            return 0;

        //分别计算左子树和右子树的深度
        int leftDepth = maxDepth(root->left) + 1;
        int rightDepth = maxDepth(root->right) + 1;

        return leftDepth > rightDepth ? leftDepth: rightDepth;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

二叉树的最小深度

给定一个二叉树,找出其最小深度。 
二叉树的最小深度为根节点到最近叶子节点的距离。

两种实现方法:

一种就是计算左子树和右子树深度的时候,判断是否等于0,如果等于0,说明该子树不存在,深度赋值为最大值。

int minDepth(TreeNode *root) {
        if(root == NULL)
            return false;
        if(root->left == NULL && root->right == NULL)
            return 1;

        int leftDepth = minDepth(root->left);
        if(leftDepth == 0)
            leftDepth = INT_MAX;

        int rightDepth = minDepth(root->right);
        if(rightDepth == 0)
            rightDepth = INT_MAX;

        return leftDepth < rightDepth ? (leftDepth + 1) : (rightDepth + 1);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

第二种就是判断左子树或右子树是否为空,若左子树为空,则返回右子树的深度,反之返回左子树的深度,如果都不为空,则返回左子树和右子树深度的最小值。

int minDepth(TreeNode *root) {
        if(root == nullptr)
            return 0;

        //判断左子树或右子树是否为空
        //若左子树为空,则返回右子树的深度,反之返回左子树的深度
        if(root->left == nullptr)
            return minDepth(root->right) + 1;
        if(root->right == nullptr)
            return  minDepth(root->left) + 1;

        //如果都不为空,则返回左子树和右子树深度的最小值
        int leftDepth = minDepth(root->left) + 1;
        int rightDepth = minDepth(root->right) + 1;

        return leftDepth < rightDepth ? leftDepth: rightDepth;
    }

猜你喜欢

转载自blog.csdn.net/snailcpp/article/details/80041159