LeetCode(111):二叉樹的最小深度


Easy!

題目描述:

給定一個二叉樹,找出其最小深度。

最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。

說明: 葉子節點是指沒有子節點的節點。

示例:

給定二叉樹 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度  2.

解題思路:

二叉樹的經典問題之最小深度問題就是就最短路徑的節點個數,還是用深度優先搜索DFS來完成,萬能的遞歸啊。。。請看代碼。

C++解法一:

 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  */
10 class Solution {
11 public:
12     int minDepth(TreeNode *root) {
13         if (root == NULL) return 0;
14         if (root->left == NULL && root->right == NULL) return 1;
15         
16         if (root->left == NULL) return minDepth(root->right) + 1;
17         else if (root->right == NULL) return minDepth(root->left) + 1;
18         else return 1 + min(minDepth(root->left), minDepth(root->right));
19     }
20     
21 };

 


免責聲明!

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



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