p = p.next;
if (poll.left != null) {
//当前出队的节点有左孩子,则左孩子入队
queue.add(poll.left);
}
if (poll.right != null) {
//当前出队的节点有右孩子,则右孩子入队
queue.add(poll.right);
}
}
//for循环走完后就遍历完了一层,将存储该层节点的链表第一个有实际值的节点入队
list.add(head.next);
}
//将可变长的数组转化成定长数组(因为函数的返回值要求了返回一个定长数组ListNode[])
return list.toArray(new ListNode[list.size()]);
}
}
Q4.4 检查平衡性
实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
/**
-
Definition for a binary tree node.
-
public class TreeNode {
-
int val;
-
TreeNode left;
-
TreeNode right;
-
TreeNode(int x) { val = x; }
-
}
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
int x=depth(root.left);
int y=depth(root.right);
if(x-y>=-1&&x-y<=1){
boolean m=isBalanced(root.left);
boolean n=isBalanced(root.right);
return m&&n;
}else{
return false;
}
}
public int depth(TreeNode root){
if(root==null) return 0;
return Math.max(depth(root.left),depth(root.right))+1;
}
}
Q4.5 合法二叉搜索树
实现一个函