-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_bottom_left_tree_value.cpp
104 lines (86 loc) · 2.49 KB
/
find_bottom_left_tree_value.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
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// https://leetcode.com/problems/find-bottom-left-tree-value/?tab=Description
// Mar 04, 2017
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
int findBottomLeftValue(TreeNode* root)
{
TreeNode* leftNode = NULL;
int prevLayer = -1;
// BFS traversal
queue<pair<TreeNode*,int> > Q;
Q.push(make_pair(root,0));
while (!Q.empty())
{
pair<TreeNode*,int> elem = Q.front();
Q.pop();
TreeNode* node = elem.first;
int curLayer = elem.second;
if (curLayer != prevLayer)
{
// leftmost element of the curLayer
leftNode = node;
prevLayer = curLayer;
}
if (node->left)
{
Q.push(make_pair(node->left, curLayer+1));
}
if (node->right)
{
Q.push(make_pair(node->right, curLayer+1));
}
}
return leftNode->val;
}
};
int main(int argc, char* argv[])
{
int test_case = 2;
switch (test_case)
{
case 1:
{
TreeNode* node1 = new TreeNode(1);
TreeNode* node2 = new TreeNode(2);
TreeNode* node3 = new TreeNode(3);
node2->left = node1;
node2->right = node3;
Solution sln;
int leftVal = sln.findBottomLeftValue(node2);
cout << "left val: " << leftVal << endl;
break;
}
case 2:
{
TreeNode* node1 = new TreeNode(1);
TreeNode* node2 = new TreeNode(2);
TreeNode* node3 = new TreeNode(3);
TreeNode* node4 = new TreeNode(4);
TreeNode* node5 = new TreeNode(5);
TreeNode* node6 = new TreeNode(6);
TreeNode* node7 = new TreeNode(7);
node1->left = node2;
node1->right = node3;
node2->left = node4;
node3->left = node5;
node3->right = node6;
node5->left = node7;
Solution sln;
int leftVal = sln.findBottomLeftValue(node1);
cout << "left val: " << leftVal << endl;
break;
}
}
return 0;
}