Java---判断一棵树是否为平衡二叉树

Java—判断一棵树是否为平衡二叉树

思路:从根节点开始,先判断左右子树的高度差是否超过1,然后接着判断左右子树是否是平衡二叉树

代码实现:

/**
 * @Author shall潇
 * @Date 2021/3/4
 * @Description 平衡二叉树就是左子树和右子树的高度差不能超过1,且左右子树必须是平衡二叉树
 *
 */
public class BinaryBalanceTree {
    public boolean isBalancedTree(Node root){//判断左右子树是否为平衡二叉树
        if(root==null)return true;

        if(Math.abs(getDepth(root.left)-getDepth(root.right))<=1){  //如果左右子树高度相差在1以及以内,则是
            return isBalancedTree(root.right) && isBalancedTree(root.right);
        }else {
            return false;
        }

    }
    public int getDepth(Node root){
        if(root==null)return 0;
        int left = getDepth(root.left);     //获取左子树高度
        int right = getDepth(root.right);   //获取右子树高度
        return (left>right?left:right)+1;   
    }
    class Node{     //创建二叉树的数据结构
        int date;
        Node left;
        Node right;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43288259/article/details/114376449
今日推荐