-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmin_depth_of_tree.cpp
26 lines (26 loc) · 1004 Bytes
/
min_depth_of_tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if( root == NULL) return 0;
int lHeight = minDepth(root->left);
// as nodes can be max 10^5 for skewed tree max height can be same, if not present will take 1 as min
if(lHeight == 0) lHeight = (int)1e6;
int rHeight = minDepth(root->right);
// as nodes can be max 10^5 for skewed tree max height can be same, if not present will take 1 as min
if(rHeight == 0) rHeight = (int)1e6;
// if it's leave node return 1
if(lHeight == rHeight && rHeight == (int)1e6) return 1;
return min(lHeight, rHeight)+1;
}
};