LeetCode:Find Largest Value in Each Tree Row

来源:互联网 发布:四旋翼飞控编程 编辑:程序博客网 时间:2024/06/07 01:15

题目链接:https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/

主要思路:使用宽度优先搜索算法,遍历完一层的结点,比较得出该行的最大值,然后继续遍历下一层。

代码如下:

    vector<int> largestValues(TreeNode* root) {        vector<TreeNode*> now_row;        vector<int> result;        if (root != NULL) {            now_row.push_back(root);            result.push_back(root->val);            while(!now_row.empty()) {                vector<TreeNode*> next_row;                vector<int> row_val;                while(!now_row.empty()) {                    TreeNode *temp = now_row.back();                    now_row.pop_back();                    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);                    }                }                int max;                if (!row_val.empty()) {                    max = row_val[0];                    for(int i = 1; i < row_val.size(); i++) {                        if (row_val[i] > max) {                            max = row_val[i];                        }                    }                    result.push_back(max);                }                now_row.clear();                for(int i = 0; i < next_row.size(); i++) {                    now_row.push_back(next_row[i]);                }            }        }        return result;    }


阅读全文
0 0