问题:给定一颗二叉树,判定其是否为平衡二叉树。
二叉树的结构为:
//Definition for binary tree
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
方法一:首先可以求出每一个节点的高度(采用递归的方法),然后再判断每一个节点是否符合平衡的条件(即| leftHeight-rightHeight | <= 1)(采用递归的方法)。此方法的时间复杂度应该是O(n^2)
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null)
return true;
if(Math.abs(getHeight(root.left)-getHeight(root.right)) <=1 && isBalanced(root.left) && isBalanced(root.right))
return true;
else
return false;
}
public int getHeight(TreeNode root){
if(root == null)
return 0;
return Math.max(getHeight(root.left),getHeight(root.right)) + 1;
}
}
方法二:此方法只使用一次递归,在遍历树的同时也做树是否平衡的判断。此方法的时间复杂度应该是O(n)
public class Solution {
public boolean isBalance = true;
public boolean isBalanced(TreeNode root){
maxDepth(root);
return isBalance;
}
public int maxDepth(TreeNode root){
if(root == null)
return 0;
int leftH = maxDepth(root.left);
int rightH = maxDepth(root.right);
if(Math.abs(leftH - rightH) > 1)
isBalance = false;
return Math.max(leftH,rightH) + 1;
}
}