LeetCode OJ-513.Find Bottom Left Tree Value
题目描述
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.
Subscribe to see which companies asked this question.
题目理解
题目要求二叉树的最底下一层最左边的节点,注意,这里的最左边的节点可能是一个节点的左子节点,也可能是一个节点的右子节点。另外,这只是普通的二叉树,并未说明是搜索二叉树,并不具备特殊性质。这里采用广度优先搜索是较好的处理方式,逐层搜索,使用队列queue辅助。
Code
typedef TreeNode tree_t;
class Solution {
public:
int findBottomLeftValue(TreeNode* t) {
int res = 0;
tree_t *tmp;
queue<tree_t *> q;
size_t sz = 0;
q.push(t);
while (!q.empty()) {
sz = q.size();
res = q.front()->val; // 记录每层的最左节点的值
while (sz--) { // 将该层的其余节点的子节点加入队列,则可舍弃,因为只需关注最左
tmp = q.front();
q.pop();
if (tmp->left != 0) {
q.push(tmp->left);
}
if (tmp->right != 0) {
q.push(tmp->right);
}
}
}
return res;
}
};