515.在每个树行中找最大值 ,116.填充每个节点的下一个右侧节点指针,117.填充每个节点的下一个右侧节点指针II,104.二叉树的最大深度,111.二叉树的最小深度
515.在每个树行中找最大值力扣题目链接
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new LinkedList<>();
Queue<TreeNode> que = new LinkedList<>();
if(root == null) return res;
que.offer(root);
while(!que.isEmpty()){
int size = que.size();
int max = Integer.MIN_VALUE; //设置最小值
for(int i = 0; i < size; i++){
TreeNode node = que.poll();
max = Math.max(max,node.val) //获取当前行最大值
if(node.left != null) que.offer(node.left);
if(node.right != null) que.offer(node.right);
}
res.add(max);
}
return res;
}
}
Integer.MIN_VALUE为int类型最小值
Integer.MAX_VALUE为int类型最大值
116.填充每个节点的下一个右侧节点指针力扣题目链接
117.填充每个节点的下一个右侧节点指针II力扣题目链接
116规定完整二叉树,117没规定,但其实做法是一样的
class Solution {
public Node connect(Node root) {
Queue<Node> que = new LinkedList<>();
if(root != null)que.offer(root);
while(!que.isEmpty()){
int size = que.size();
Node pre = null;
Node cur = null;
for(int i = 0; i < size; i++){
if(i == 0){
pre = que.poll(); //取出本行头节点
cur = pre;
}else{
cur = que.poll();
pre.next = cur; // 本层前一个节点 next 指向当前节点
pre = pre.next;
}
if(cur.left != null)que.offer(cur.left);
if(cur.right != null)que.offer(cur.right);
}
pre.next=null // 本层最后一个节点 next 指向 null
}
return root;
}
}
根据做题发现后面pre.next=null可以省略,但省略后不好理解
104.二叉树的最大深度力扣题目链接
class Solution {
public int maxDepth(TreeNode root) {
if(root == null)return 0;
int l = maxDepth(root.left);
int r = maxDepth(root.right);
return Math.max(l,r) + 1;
}
}
111.二叉树的最小深度力扣题目链接
class Solution {
public int minDepth(TreeNode root){
if(root == null)return 0;
Queue<TreeNode> que = new LinkedList<>();
que.offer(root);
int depth = 0;
while(!que.isEmpty()){
int size = que.size();
depth++;
for(int i = 0; i < size; i++){
TreeNode cur = que.poll();
if(cur.left == null && cur.right == null){
return depth;
}
if(cur.left != null)que.offer(cur.left);
if(cur.right != null)que.offer(cur.right);
}
}
return depth;
}
}