一、自顶向下的递归
判断每个结点本身是不是平衡二叉树,再判断他的左右子树是不是平衡树
缺点:重复算很多次高度
Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
int leftDepth=Depth(root.left);
int rightDepth=Depth(root.right);
if((leftDepth-rightDepth>1)||(rightDepth-leftDepth>1)) return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
public int Depth(TreeNode root){
if(root==null) return 0;
int leftDepth=Depth(root.left);
int rightDepth=Depth(root.right);
return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
}
}
二、自下而上
从下往上算高度的时候 判断是否为平衡树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
return Depth(root)>=0;
}
public int Depth(TreeNode root){
if(root==null) return 0;
int leftDepth=Depth(root.left);
int rightDepth=Depth(root.right);
if(leftDepth<0||rightDepth<0||(leftDepth-rightDepth)>1||(rightDepth-leftDepth)>1) return -1;//小技巧
return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
}
}