leetcode 513. Find Bottom Left Tree Value
1.题目
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
假设根结点不为空。
2.分析
BFS:按层来遍历节点,返回最底层左边第一个节点的值。
如果是从左往右遍历,需要用一个变量来记录当前层的高度。
如果是从右往左遍历,直接返回遍历的最后一个节点的值即可。这种方法是比较好的。
3.代码
BFS,从右往左遍历。直接返回最后一个遍历的节点的值。
最后一个遍历的节点一定是最底层的最左边的节点。
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> nodes;
nodes.push(root);
while (!nodes.empty()) {
root = nodes.front();
nodes.pop();
if (root->right)
nodes.push(root->right);
if (root->left)
nodes.push(root->left);
}
return root->val;
}
};
还没有评论,来说两句吧...