-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathFind BottomLeftTreeValue.cpp
45 lines (37 loc) · 1.06 KB
/
Find BottomLeftTreeValue.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getLevel(TreeNode* root, int level){
if(!root){
return level-1;
}
return max(level, max(getLevel(root->left, level+1), getLevel(root->right, level+1)));
}
void getLeft(TreeNode* root, int level, int MAX_LEVEL, bool& found, int& ans){
if(found || !root){
return;
}
else if(level == MAX_LEVEL){
ans = root->val;
found = true;
return;
}
getLeft(root->left, level+1, MAX_LEVEL, found, ans);
getLeft(root->right, level+1, MAX_LEVEL, found, ans);
}
int findBottomLeftValue(TreeNode* root) {
int maxLevel = getLevel(root, 0);
bool found = false;
int ans;
getLeft(root, 0, maxLevel, found, ans);
return ans;
}
};