剑指offer39-平衡二叉树

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

思路:递归。递归求取左右子树的高度,然后进行判断高度差是否大于1。

代码:

 

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null)
            return true;
        int depthleft = TreeDepth(root.left);
        int depthright = TreeDepth(root.right);
        int cw = depthleft-depthright;
        if(cw<-1 || cw>1) return false;
        return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
            
        
        
    }
    public int TreeDepth(TreeNode root) {
        if(root==null)
            return 0;
        int nleft = TreeDepth(root.left);
        int nright = TreeDepth(root.right);
        return Math.max(nleft,nright)+1;
    } 
}

 

posted @ 2020-03-25 20:36  清心lh  阅读(110)  评论(0编辑  收藏  举报