(二叉树 BFS) leetcode513. Find Bottom Left Tree Value

时间:2021-10-23 08:29:42

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

Example 1:

Input:

    2
/ \
1 3 Output:
1

Example 2:

Input:

        1
/ \
2 3
/ / \
4 5 6
/
7 Output:
7

Note: You may assume the tree (i.e., the given root node) is not NULL.

--------------------------------------------------------------------------------------------------------------------------------

这个题就是求出二叉树的最后一层的最左边的结点的数。

可以用BFS,也可以用DFS,不过BFS相对会简单一些的。

C++代码:

/**
* 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) {
if(!root) return ;
queue<TreeNode*> q;
q.push(root);
int res = root->val;
while(!q.empty()){
int len = q.size(); //必须加上这个,如果用i==q.size(),则会出错,因为q.size()会变化。
for(int i = len; i > ; i--){
auto t = q.front();
q.pop();
if(i == len){
res = t->val;
}
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return res;
}
};