LeetCode:Find Bottom Left Tree Value
2017-10-08 15:20
471 查看
题目链接:https://leetcode.com/problems/find-bottom-left-tree-value/description/
解题思路:使用宽度优先搜索,搜索完一行的结点再继续下一行的结点,返回最后一行的左边第一个结点的值。
代码如下:
int findBottomLeftValue(TreeNode* root) {
vector<TreeNode*> now_row;
int result;
if (root != NULL) {
now_row.push_back(root);
result = root->val;
while(!now_row.empty()) {
vector<TreeNode*> next_row;
vector<int> row_val;
for(int i = 0; i < now_row.size(); i++) {
TreeNode *temp = now_row[i];
if (temp->left != NULL) {
row_val.push_back(temp->left->val);
next_row.push_back(temp->left);
}
if (temp->right != NULL) {
row_val.push_back(temp->right->val);
next_row.push_back(temp->right);
}
}
now_row.clear();
if (!next_row.empty()) {
for(int i = 0; i < next_row.size(); i++) {
now_row.push_back(next_row[i]);
}
result = now_row[0]->val;
}
}
}
return result;
}
解题思路:使用宽度优先搜索,搜索完一行的结点再继续下一行的结点,返回最后一行的左边第一个结点的值。
代码如下:
int findBottomLeftValue(TreeNode* root) {
vector<TreeNode*> now_row;
int result;
if (root != NULL) {
now_row.push_back(root);
result = root->val;
while(!now_row.empty()) {
vector<TreeNode*> next_row;
vector<int> row_val;
for(int i = 0; i < now_row.size(); i++) {
TreeNode *temp = now_row[i];
if (temp->left != NULL) {
row_val.push_back(temp->left->val);
next_row.push_back(temp->left);
}
if (temp->right != NULL) {
row_val.push_back(temp->right->val);
next_row.push_back(temp->right);
}
}
now_row.clear();
if (!next_row.empty()) {
for(int i = 0; i < next_row.size(); i++) {
now_row.push_back(next_row[i]);
}
result = now_row[0]->val;
}
}
}
return result;
}
相关文章推荐
- [LeetCode]Find Bottom Left Tree Value
- leetcode 513 Find Bottom Left Tree Value C++
- LeetCode: Find Bottom Left Tree Value
- LeetCode 513 Find Bottom Left Tree Value (BFS)
- 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
- LeetCode- Find Bottom Left Tree Value
- LeetCode - 513 - 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
- 【Leetcode513 Find Bottom left Tree Value】树的遍历
- LeetCode——Find Bottom Left Tree Value
- [LeetCode] Find Bottom Left Tree Value 寻找最左下树结点的值
- lintcode/leetcode由易至难第18题:Find Bottom Left Tree Value