leetcode——面试题55.II平衡二叉树

class Solution {
    public boolean isBalanced(TreeNode root) {
        //判断一个树是不是平衡二叉树
        //应该是用递归了吧,判断左右子树的高度相差是不是超过1
        //但是如何记录树的高度呢,左右子树的高度分别记录的话,应该如何进行呢?
        if(root == null){
            return true;
        }else{
            int a = checkBalanced(root.left);
            int b = checkBalanced(root.right);
            if(Math.abs(a-b)>1){
                return false;
            }else{
                return isBalanced(root.left)&&isBalanced(root.right);
            }
        }
    }

    private int checkBalanced(TreeNode node) {
        if(node == null){
            return 0;
        }else{
            return Math.max(checkBalanced(node.left)+1,checkBalanced(node.right)+1);
        }
    }
}

 

 也不知道具体算是什么算法,就想着套递归,把逻辑屡清楚就套进去了……

 

——2020.6.18

 

posted @ 2020-06-18 09:23  欣姐姐  阅读(128)  评论(0编辑  收藏  举报