minnum depthe of binary tree

minnum depthe of binary tree

Logic is important

 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 ) {
14             return 0;
15         }
16         if ( root->left && root->right ) {
17             return min(minDepth(root->left),minDepth(root->right))+1;
18         }
19         if ( root->left ) {
20             return minDepth(root->left)+1;
21         }
22         if ( root->right ) {
23             return minDepth(root->right)+1;
24         }
25         return 1;
26     }
27 };

Loading Disqus comments...
Table of Contents