给定一个二叉树,在树的最后一行找到最左边的值。
示例 1:
输入:
2
/ \
1 3
输出:
1
示例 2:
输入:
1
/ \
2 3
/ / \
4 5 6
/
7
输出:
7
解题思路:观察特点,发现左下角的值,是层次遍历的第一个,我们可以记录 当floor 加1 之后,更新一下 左下角的值
/**
* 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:
TreeNode *res=NULL;
struct node{
TreeNode* tree;
int level;
};
int findBottomLeftValue(TreeNode* root) {
queue<node> q;
TreeNode *res = root;
int ans;
int f = 0;
node tmp;
tmp.tree = root;
tmp.level = 1;
q.push(tmp);
while(!q.empty()){
tmp = q.front();
q.pop();
if(tmp.level>f){
// cout<<tmp.level<<endl;
ans= tmp.tree->val;
// cout<<ans<<endl;
f = tmp.level;
}
node now;
if(tmp.tree->left!=NULL){
now.tree = tmp.tree->left;
now.level = tmp.level+1;
// cout<<now.tree->val<<endl;
q.push(now);
}
if(tmp.tree->right!=NULL){
now.tree = tmp.tree->right;
now.level = tmp.level+1;
// cout<<now.tree->val<<endl;
q.push(now);
}
}
return ans;
}
};