LeetCode:Find Bottom Left Tree Value

来源:互联网 发布:图片尺寸修改软件app 编辑:程序博客网 时间:2024/05/17 03:57

题目链接: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;    }