515. 在每个树行中找最大值
题目链接:
题目描述
给定一棵二叉树的根节点 root
,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
解释:
1
/ \
3 2
/ \ \
5 3 9
示例2:
输入: root = [1,2,3]
输出: [1,3]
解释:
1
/ \
2 3
示例3:
输入: root = [1]
输出: [1]
示例4:
输入: root = [1,null,2]
输出: [1,2]
解释:
1
\
2
示例5:
输入: root = []
输出: []
提示:
-
二叉树的节点个数的范围是
[0,104]
-
-231 <= Node.val <= 231 - 1
题解
思路:层次遍历,找出每一层的最大值
代码(C++):
struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int value) : val(value), left(nullptr), right(nullptr) {} }; class Solution { public: vector<int> largestValues(TreeNode* root) { queue<TreeNode*> que; vector<int> result; if (root != nullptr) que.push(root); while (!que.empty()) { int size = que.size(); TreeNode* node1 = que.front(); int max = node1->val; for (int i = 0; i < size; i++) { TreeNode* node2 = que.front(); que.pop(); if (max < node2->val) max = node2->val; if (node2->left) que.push(node2->left); if (node2->right) que.push(node2->right); } result.push_back(max); } return result; } };
代码(Java):
class Solution { public List<Integer> largestValues(TreeNode root) { Deque<TreeNode> que = new LinkedList<>(); if (root != null) que.offer(root); List<Integer> result = new ArrayList<>(); while (!que.isEmpty()) { int size = que.size(); TreeNode node1 = que.peek(); int max = node1.val; for (int i = 0; i < size; i++) { TreeNode node2 = que.poll(); if (max < node2.val) max = node2.val; if (node2.left != null) que.offer(node2.left); if (node2.right != null) que.offer(node2.right); } result.add(max); } return result; } }
分析:
-
-
空间复杂度:O(N)