Find Bottom Left Tree Value
2018-03-21 16:32
162 查看
Description: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.
思路:该题目是找二叉树的最左边的 叶子结点,首先想到的是用BFS,对二叉树进行层序遍历,最关键的是要记录当前二叉树的层级,又利用了一个队列记录了每个结点的层级
/**
* 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;
queue<int> level;
int l = 1;
q.push(root);
level.push(l);
4000
TreeNode* tmp = root;
int ret = root->val;
while(!q.empty())
{
TreeNode* t = q.front();
int ll = level.front();
q.pop();
level.pop();
if(l != ll)
{
l = ll;
ret = t->val;
}
ll = ll + 1;
if(t->left != NULL)
{
q.push(t->left);
level.push(ll);
}
if(t->right != NULL)
{
q.push(t->right);
level.push(ll);
}
}
return ret;
}
};
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.
思路:该题目是找二叉树的最左边的 叶子结点,首先想到的是用BFS,对二叉树进行层序遍历,最关键的是要记录当前二叉树的层级,又利用了一个队列记录了每个结点的层级
/**
* 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;
queue<int> level;
int l = 1;
q.push(root);
level.push(l);
4000
TreeNode* tmp = root;
int ret = root->val;
while(!q.empty())
{
TreeNode* t = q.front();
int ll = level.front();
q.pop();
level.pop();
if(l != ll)
{
l = ll;
ret = t->val;
}
ll = ll + 1;
if(t->left != NULL)
{
q.push(t->left);
level.push(ll);
}
if(t->right != NULL)
{
q.push(t->right);
level.push(ll);
}
}
return ret;
}
};
相关文章推荐
- [LeetCode]Find Bottom Left Tree Value
- leetcode513 FindBottomLeftTreeValue Java
- LeetCode Find Bottom Left Tree Value [Medium]
- LeetCode@513_Find_Bottom_Left_Tree_Value
- 算法课 第四周 Find Bottom Left Tree Value
- No.513 Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- 第十周算法分析与设计: Find Bottom Left Tree Value
- Find Bottom Left Tree Value宽度优先遍历算法详解
- 513:find bottom left tree value
- leetcode 513 Find Bottom Left Tree Value
- LeetCode 513 Find Bottom Left Tree Value (BFS)
- Medium:Find Bottom Left Tree Value
- Find Bottom Left Tree Value |找到二叉树最后一层的最左边的节点的值
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- LeetCode算法问题15 —— Find Bottom Left Tree Value
- 513[Medium]:Find Bottom Left Tree Value
- LeetCode Find Bottom Left Tree Value
- LeetCode: Find Bottom Left Tree Value