二叉樹的最大深度和最小深度(編程實現)


1. 二叉樹的最大深度:(LeetCode104)  

Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

最大深度也是到葉子節點的長度,但是因為是求最大深度,單個孩子為空的非葉子節點不會干擾到結果,因此用最簡潔的處理方式就可以搞定。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode *root) {
        if(!root) return 0;
        int leftDepth = maxDepth(root -> left) + 1;      // 遞歸調用左子樹
        int rightDepth = maxDepth(root -> right) + 1;    // 遞歸調用右子樹
        return max(leftDepth, rightDepth);               // 返回左右子樹中較大的一個,  注意最后不用加 1。
    }
};

2. 二叉樹的最小深度(LeetCode111)

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

因為深度是必須到葉子節點的距離,因此使用深度遍歷時,不能單純的比較左右子樹的遞歸結果返回較小值,因為對於有單個孩子為空的節點,為空的孩子會返回0,但這個節點並非葉子節點,故返回的結果是錯誤的。因此,當發現當前處理的節點有單個孩子是空時,返回一個極大值INT_MAX,防止其干擾結果。

1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
 class Solution {
  public:
      int minDepth(TreeNode *root) {
          if(!root) return 0;
          if(!root -> left && !root -> right) return 1;   //Leaf means should return depth.
          int leftDepth = 1 + minDepth(root -> left);
          leftDepth = (leftDepth == 1 ? INT_MAX : leftDepth);
          int rightDepth = 1 + minDepth(root -> right);
          rightDepth = (rightDepth == 1 ? INT_MAX : rightDepth);  //If only one child returns 1, means this is not leaf, it does not return depth.
         return min(leftDepth, rightDepth);
     }
 };

 

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode *root) {
        if (root == NULL) return 0;
        if (root->left == NULL && root->right == NULL) return 1;
        
        if (root->left == NULL) return minDepth(root->right) + 1;
        else if (root->right == NULL) return minDepth(root->left) + 1;
        else return 1 + min(minDepth(root->left), minDepth(root->right));
    }
    
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM