Description
Given a binary tree, find the leftmost value in the last row of the tree.
Analysis
sol1:
二叉树先序遍历,中-左-右,最左结点总是第一个遍历到,所以多记录一个附加值高度,当高度增加时,肯定是该层第一个结点。
sol2:
二叉树层次遍历,用辅助队列,遍历每层时,记录每层的第一个结点作返回值。
sol1:
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
int cur_depth = 1, max_depth = 1, ret = root->val;
helper(root, cur_depth, max_depth, ret);
return ret;
}
void helper(TreeNode *root, int cur_depth, int &max_depth, int &ret) {
if (root == 0)
return;
if (cur_depth > max_depth) {
max_depth = cur_depth;
ret = root->val;
}
helper(root->left, cur_depth + 1, max_depth, ret);
helper(root->right, cur_depth + 1, max_depth, ret);
}
};
sol2:
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
if (root == 0)
return -1;
queue<TreeNode *> que;
que.push(root);
int ret;
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i ++) {
TreeNode *temp = que.front();
que.pop();
if (i == 0)
ret = temp->val;
if (temp->left)
que.push(temp->left);
if (temp->right)
que.push(temp->right);
}
}
return ret;
}
};