问题:
给定二叉树,求每层最大节点,返回。
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 };