-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathfind-bottom-left-tree-value.cpp
59 lines (54 loc) · 1.45 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
// Time: O(n)
// Space: O(h)
/**
* 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 result = 0, max_depth = 0;
findBottomLeftValueHelper(root, 0, &max_depth, &result);
return result;
}
private:
void findBottomLeftValueHelper(TreeNode *root, int curr_depth, int *max_depth, int *bottom_left_value) {
if (!root) {
return;
}
if (!root->left && !root->right &&
curr_depth + 1 > *max_depth) {
*max_depth = curr_depth + 1;
*bottom_left_value = root->val;
return;
}
findBottomLeftValueHelper(root->left, curr_depth + 1, max_depth, bottom_left_value);
findBottomLeftValueHelper(root->right, curr_depth + 1, max_depth, bottom_left_value);
}
};
// Time: O(n)
// Space: O(w)
class Solution2 {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode *> q;
q.emplace(root);
TreeNode *node = nullptr;
while (!q.empty()) {
node = q.front();
q.pop();
if (node->right) {
q.emplace(node->right);
}
if (node->left) {
q.emplace(node->left);
}
}
return node->val;
}
};