LeetCode- Find Bottom Left Tree Value
2017-09-24 11:33
295 查看
题目:
Given a binary tree, find the leftmost value in the last row of the tree.
Example 1:
Example 2:
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;
}
};
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;
}
};
相关文章推荐
- LeetCode Find Bottom Left Tree Value
- LeetCode Find Bottom Left Tree Value
- [LeetCode]Find Bottom Left Tree Value
- Leetcode 513 Find Bottom Left Tree Value
- 【Leetcode513 Find Bottom left Tree Value】树的遍历
- LeetCode——Find Bottom Left Tree Value
- LeetCode Find Bottom Left Tree Value [Medium]
- [LeetCode] Find Bottom Left Tree Value 寻找最左下树结点的值
- leetcode 513 Find Bottom Left Tree Value
- LeetCode - 513 - Find Bottom Left Tree Value
- LeetCode之Find Bottom Left Tree Value
- leetcode 513 Find Bottom Left Tree Value C++
- LeetCode 513 Find Bottom Left Tree Value(二叉树层序遍历)
- LeetCode: Find Bottom Left Tree Value
- lintcode/leetcode由易至难第18题:Find Bottom Left Tree Value
- leetcode513 FindBottomLeftTreeValue Java
- [LeetCode]513 Find Bottom Left Tree Value(BFS)
- 【LeetCode】Find Bottom Left Tree Value 解题报告
- [LeetCode]Find Bottom Left Tree Value 寻找二叉树最左树叶的值
- LeetCode 513 Find Bottom Left Tree Value (BFS)