-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path513 Find Bottom Left Tree Value
71 lines (70 loc) · 1.91 KB
/
513 Find Bottom Left Tree Value
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
bfs:
/**
* 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 findBottomLeftValue(TreeNode* root) {
int ans;
queue<TreeNode*>q;
queue<int>level;
q.push(root);
level.push(0);
int x=-1;
while(q.size()){
TreeNode*node=q.front();
q.pop();
int lev=level.front();
level.pop();
if(node->left!=NULL){
q.push(node->left);
level.push(lev+1);
}
if(node->right!=NULL){
q.push(node->right);
level.push(lev+1);
}
if(lev>x){
x=lev;
ans=node->val;
}
}
return ans;
}
};
============================================================================================================================
递归 from discuss
/**
* 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 findBottomLeftValue(TreeNode* root) {
int max_depth=0,depth=0;
int leftmost_val=root->val;
find(root,max_depth,depth,leftmost_val);
return leftmost_val;
}
void find(TreeNode*node,int&maxdepth,int depth,int&leftmostval){
//maxdepth是对max_depth的引用,每次depth大于maxdepth都会修改maxdepth的值
if(node==NULL)return;
find(node->left,maxdepth,depth+1,leftmostval);
find(node->right,maxdepth,depth+1,leftmostval);
if(depth>maxdepth){//该判断只在n+1层的最左端节点为true
maxdepth=depth;
leftmostval=node->val;
}
}
};