[LeetCode] Find Bottom Left Tree Value

513. Find Bottom Left Tree Value

Given the root of a binary tree, return the leftmost value in the last row of the tree.

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> q;
int res;
q.push(root);
while(!q.empty()) {
int sz = q.size();
res = q.front()->val;
while(sz--) {
auto u = q.front(); q.pop();
if(u->left) q.push(u->left);
if(u->right) q.push(u->right);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/14/PS/LeetCode/find-bottom-left-tree-value/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.