题目:
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.
解读:给予一颗二叉树,找到最深的节点中最左边的那个并输出val值。
思考:采用BFS层次遍历算法,为使的最后的结果输出的是最左边的节点,则queue先push右节点再push左节点。
代码:
/**
* 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*> q;
int answer;
if(root != NULL)
q.push(root);
while(q.size()){
if(q.front()->right !=NULL)
q.push(q.front()->right);
if(q.front()->left !=NULL)
q.push(q.front()->left);
answer = q.front()->val;
q.pop();
}
return answer;
}
};