首页 > 其他 > 详细

515. Find Largest Value in Each Tree Row

时间:2021-03-03 14:47:00      阅读:36      评论:0      收藏:0      [点我收藏+]

问题:

给定二叉树,求每层最大节点,返回。

Example 1:
Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]

Example 2:
Input: root = [1,2,3]
Output: [1,3]

Example 3:
Input: root = [1]
Output: [1]

Example 4:
Input: root = [1,null,2]
Output: [1,2]

Example 5:
Input: root = []
Output: []
 
Constraints:
The number of nodes in the tree will be in the range [0, 104].
-231 <= Node.val <= 231 - 1

 

example 1:

技术分享图片

 

 

解法:BFS

queue存储每层node,处理每层节点时,对每个节点求max。

 

代码参考:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     vector<int> largestValues(TreeNode* root) {
15         vector<int> res;
16         queue<TreeNode*> q;
17         if(root) q.push(root);
18         int tmpmax;
19         while(!q.empty()) {
20             int sz = q.size();
21             tmpmax = q.front()->val;
22             for(int i=0; i<sz; i++) {
23                 TreeNode* cur = q.front();
24                 q.pop();
25                 tmpmax = max(tmpmax, cur->val);
26                 if(cur->left) q.push(cur->left);
27                 if(cur->right) q.push(cur->right);
28             }
29             res.push_back(tmpmax);
30         }
31         return res;
32     }
33 };

 

515. Find Largest Value in Each Tree Row

原文:https://www.cnblogs.com/habibah-chang/p/14473780.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!