题目描述
实现一个函数,检查二叉树是否平衡,平衡的定义如下,对于树中的任意一个结点,其两颗子树的高度差不超过1。
给定指向树根结点的指针TreeNode* root,请返回一个bool,代表这棵树是否平衡。
思路1这种后来证实是错误做法,虽然通过了,但下面的这种情况是平衡二叉树却不能检测出来:
思路1:(这种是低效的。但是比较容易想)
先序遍历 求深度 取深度 放入集合中。最后将集合 遍历 比较最大值 跟最小值 。
注意 某一节点的左或右子节点为空。 就要放入集合了,这里是或,而不是并且。因为它在其父节点处 它算最后的子节点了。
import java.util.*;
import java.util.ArrayList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class Balance {
public boolean isBalance(TreeNode root) {
// write code here
if(root==null)return false;
ArrayList<Integer> arrayList = new ArrayList<>();
int level = 1;
preorder(root,arrayList,level);
int max = arrayList.get(0);
int min = arrayList.get(0);
for(Integer a:arrayList ){
if(max<a)max = a ;
if(min>a)min = a;
}
if(max-min>1)return false;
return true;
}
public void preorder(TreeNode root,ArrayList<Integer> arrayList,int level){
if(root.left!=null)preorder(root.left,arrayList,level+1);
if(root.right!=null)preorder(root.right,arrayList,level+1);
if(root.left==null||root.right==null){
arrayList.add(level);
}
}
}
正解:
思路:后序遍历取它们的高度,然后依次判定它们的左右子树高度,返回它们的高度。并且需要递归它们的子树。时间复杂度o(n2)
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class Balance {
public boolean isBalance(TreeNode root) {
// write code here
if(root==null)return true;
int left = getDeep(root.left);
int right = getDeep(root.right);
if(Math.abs(left-right)>1)return false;
//这里必须递归返回
else{
return isBalance(root.left)&&isBalance(root.right);
}
}
public int getDeep(TreeNode root){
if(root!=null){
int left = getDeep(root.left);
int right = getDeep(root.right);
return left>right?left+1:right+1;
}else{
return 0;
}
}
}