您的位置:首页 > 产品设计 > UI/UE

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: