LeetCode之Find Bottom Left Tree Value
2017-07-05 22:03
399 查看
本题的意思是给定一个二叉树,求其最底层的最左边的节点的值。(该二叉树不为空。)
我采用BFS算法来解决此题。对给定的二叉树从右至左进行BFS,则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*> bfs;
bfs.push(root);
while (!bfs.empty()) {
root = bfs.front();
bfs.pop();
if (root -> right != NULL) {
bfs.push(root -> right);
}
if (root -> left != NULL) {
bfs.push(root -> left);
}
}
return root -> val;
}
};
我采用BFS算法来解决此题。对给定的二叉树从右至左进行BFS,则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*> bfs;
bfs.push(root);
while (!bfs.empty()) {
root = bfs.front();
bfs.pop();
if (root -> right != NULL) {
bfs.push(root -> right);
}
if (root -> left != NULL) {
bfs.push(root -> left);
}
}
return root -> val;
}
};
相关文章推荐
- [LeetCode]Find Bottom Left Tree Value
- leetcode513 FindBottomLeftTreeValue Java
- leetcode 513 Find Bottom Left Tree Value
- [LeetCode]513 Find Bottom Left Tree Value(BFS)
- LeetCode- Find Bottom Left Tree Value
- LeetCode Find Bottom Left Tree Value
- 【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
- [LeetCode]Find Bottom Left Tree Value 寻找二叉树最左树叶的值
- LeetCode 513 Find Bottom Left Tree Value(二叉树层序遍历)
- lintcode/leetcode由易至难第18题:Find Bottom Left Tree Value
- LeetCode——Find Bottom Left Tree Value
- LeetCode Find Bottom Left Tree Value [Medium]
- [LeetCode] Find Bottom Left Tree Value 寻找最左下树结点的值
- 【Leetcode513 Find Bottom left Tree Value】树的遍历
- Leetcode 513 Find Bottom Left Tree Value
- LeetCode 513 Find Bottom Left Tree Value (BFS)
- leetcode 513 Find Bottom Left Tree Value C++