- 子问题思路:
1.先编写一个求二叉树高度的函数
2.满足完全二叉树的情况:空树或只有一个结点的树;该结点的左右子树都是完全二叉树,并且左右子树的高度差小于等于1
int hight(TreeNode root){
if(root == null)
return 0;
return hight(root.left)>hight(root.right)?
hight(root.left)+1:hight(root.right)+1;
}
boolean isComplementTree2(TreeNode root){
if(root == null)
return true;
if(root.left == null && root.right == null)
return true;
return isComplementTree(root.left)&&isComplementTree(root.right)
&&Math.abs(hight(root.left)-hight(root.right))<=1;
}
boolean isComplementTree(TreeNode root){
if(root == null)
return true;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode cur1 = queue.poll();
if(cur1 != null){
queue.offer(cur1.left);
queue.offer(cur1.right);
}
else{
break;
}
}
while(!queue.isEmpty()){
TreeNode cur2 = queue.peek();
if(cur2 != null){
return false;
}
else{
queue.poll();
}
}
return true;
}