Skip to content

Commit 86b6069

Browse files
committed
513. Find Bottom Left Tree Value
1 parent b3bd9c2 commit 86b6069

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

find-bottom-left-tree-value.cpp

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
//Using level order traversal
2+
//Runtime: 9 ms
3+
class Solution {
4+
public:
5+
int findBottomLeftValue(TreeNode* root) {
6+
int res;
7+
vector<int>temp;
8+
9+
queue<pair<int,TreeNode* > >Q;
10+
Q.push(make_pair(1, root));
11+
int maxlvl = 0;
12+
while(!Q.empty())
13+
{
14+
pair<int, TreeNode* > t = Q.front();
15+
Q.pop();
16+
17+
if(t.first > maxlvl)
18+
{
19+
maxlvl++;
20+
if(temp.size() > 0)
21+
{
22+
res = temp[0];
23+
temp.clear();
24+
}
25+
}
26+
temp.push_back(t.second->val);
27+
28+
if(t.second->left)
29+
Q.push(make_pair(t.first+1, t.second->left));
30+
31+
if(t.second->right)
32+
Q.push(make_pair(t.first+1, t.second->right));
33+
}
34+
35+
if(temp.size() > 0)
36+
res = temp[0];
37+
38+
return res;
39+
}
40+
};
41+
42+
//Runtime: 9 ms
43+
//Better solution
44+
class Solution {
45+
public:
46+
void solve(TreeNode* root, int lvl, pair<int,int> &res)
47+
{
48+
if(!root)
49+
return;
50+
solve(root->left, lvl+1, res);
51+
solve(root->right, lvl+1, res);
52+
if(lvl > res.first)
53+
{
54+
res.second = root->val;
55+
res.first = lvl;
56+
}
57+
}
58+
59+
int findBottomLeftValue(TreeNode* root) {
60+
pair<int,int>res;
61+
res.first = res.second = 0;
62+
solve(root, 1, res);
63+
return res.second;
64+
}
65+
};

0 commit comments

Comments
 (0)