难度:Medium 类型:树
513. Find Bottom Left Tree Value
题目
Given a binary tree, find the leftmost value in the last row of the tree.
概述
给定二叉树,找出其最底层的最左边元素
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
分析
其实所谓最底层节点,即为深度最深的节点,且该节点一定是叶子节点。所以只要用DFS遍历到最深的节点,这里可以采用前序遍历的方法,由于会先访问本节点的左子树,所以找到第一个深度最深的叶子节点即为最底层最左边节点。同样的,若问题求最底层最右边节点,只需要调换前序遍历左右子树遍历顺序先访问右子树即可。
当然也可以使用BFS的方法,从右子树节点开始加入队列,访问的队列中的最后一个节点就是所需要求得的最底层最左边节点。
参考代码给出的是前序遍历的方法。
代码
/**
* 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 curdepth = -1, maxdepth=-1;
int ans;
int findBottomLeftValue(TreeNode* root) {
curdepth++;
if(root->left==NULL && root->right==NULL){
if(curdepth>maxdepth){
ans = root->val;
maxdepth = curdepth;
}
}
if(root->left!=NULL)
findBottomLeftValue(root->left);
if(root->right!=NULL)
findBottomLeftValue(root->right);
curdepth--;
return ans;
}
};