【树】111. 二叉树的最小深度

题目:

解答:

 1 /**
 2  * Definition for a binary tree node.
 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     {
14         // 根节点为 NULL
15         if (NULL == root)
16         {
17             return 0;
18         }
19 
20         // 左叶子节点为 NULL
21         if (root->left == NULL)
22         {
23             return minDepth(root->right) + 1;
24         }
25         
26         // 右叶子节点为 NULL
27         if (root->right == NULL)
28         {
29             return minDepth(root->left) + 1;
30         }
31 
32         // 左右叶子节点均不为 NULL
33         return min(minDepth(root->left), minDepth(root->right)) + 1;
34     }
35 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12817738.html