LeetCode——Find Bottom Left Tree Value
Question
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.
Solution
先求出树的高度,然后层次遍历,遍历到最后一层,输出最左边的节点(也就是最后一层第一个节点,因为层次遍历采用从左到右的方式)。
Code
/**
* 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) {
int height = calcTreeHeight(root);
int count = 1;
queue<TreeNode*> childs, new_childs;
childs.push(root);
while (1) {
while(!childs.empty()) {
TreeNode* tmp = childs.front();
if (count == height)
return tmp->val;
childs.pop();
if (tmp->left != NULL)
new_childs.push(tmp->left);
if (tmp->right != NULL)
new_childs.push(tmp->right);
}
count++;
childs = new_childs;
clear(new_childs);
}
}
// 清空队列的方法
void clear( std::queue<TreeNode*> &q )
{
std::queue<TreeNode*> empty;
std::swap(q, empty );
}
int calcTreeHeight(TreeNode* root) {
if (root == NULL)
return 0;
int left = calcTreeHeight(root->left);
int right = calcTreeHeight(root->right);
return max(left, right) + 1;
}
};
Solution 2
直接层次遍历也可以,最后一层遍历结束后,直接输出最后一层的第一个节点即可。
Code 2
/**
* 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) {
queue<TreeNode*> childs, new_childs;
childs.push(root);
while (1) {
int flag = 1;
TreeNode* first;
while(!childs.empty()) {
TreeNode* tmp = childs.front();
if (flag) {
first = tmp;
flag = 0;
}
childs.pop();
if (tmp->left != NULL)
new_childs.push(tmp->left);
if (tmp->right != NULL)
new_childs.push(tmp->right);
}
if (new_childs.empty()) {
return first->val;
}
childs = new_childs;
clear(new_childs);
}
}
void clear( std::queue<TreeNode*> &q )
{
std::queue<TreeNode*> empty;
std::swap( q, empty );
}
};