题目
给定一棵二叉树的根节点 root
,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
示例2:
输入: root = [1,2,3]
输出: [1,3]
提示:
- 二叉树的节点个数的范围是
[0,10^4]
-2^31 <= Node.val <= 2^(31 - 1)
解题方法
BFS(迭代)
迭代遍历每层元素,记录最大值。
时间复杂度O(n)
,空间复杂度O(n)
C++代码:/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> result;
queue<TreeNode*> nodes;
if(root != NULL) nodes.push(root);
while(nodes.size()>0) {
int size = nodes.size();
int val = INT_MIN;
for(int i=0; i<size; i++) {
val = nodes.front()->val>val ? nodes.front()->val : val;
if(nodes.front()->left != NULL) nodes.push(nodes.front()->left);
if(nodes.front()->right != NULL) nodes.push(nodes.front()->right);
nodes.pop();
}
result.push_back(val);
}
return result;
}
};
DFS(迭代)
通过 DFS 遍历节点,更新各层最大值。
时间复杂度O(n)
,空间复杂度O(n)
C++代码:/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void DFS(TreeNode* cur, int level, vector<int>& vec) { if(cur==NULL) return; if(level<vec.size()) { vec[level] = cur->val > vec[level] ? cur->val : vec[level]; } else vec.push_back(cur->val); DFS(cur->left, level+1, vec); DFS(cur->right, level+1, vec); } vector<int> largestValues(TreeNode* root) { vector<int> result; if(root!=NULL) result.push_back(INT_MIN); int level = 0; DFS(root, level, result); return result; } };