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



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) {}
};

二叉樹的最大深度

給定一個二叉樹,找出其最大深度。
二叉樹的深度爲根節點到最遠葉子節點的距離。

如果二叉樹爲空,則深度爲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;
    }

二叉樹的最小深度

給定一個二叉樹,找出其最小深度。
二叉樹的最小深度爲根節點到最近葉子節點的距離。

兩種實現方法:

一種就是計算左子樹和右子樹深度的時候,判斷是否等於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);
    }

第二種就是判斷左子樹或右子樹是否爲空,若左子樹爲空,則返回右子樹的深度,反之返回左子樹的深度,如果都不爲空,則返回左子樹和右子樹深度的最小值。

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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章