Input a binary tree, the binary tree is determined whether or balanced tree

analysis

  • If the depth of each node of the left subtree and right subtree binary tree is not greater than 1, it is a balanced binary tree.
  • Whether to write a function of depth demand, then each node is determined, the depth and the right subtree see left subtree of the node 1 is greater than the difference between the depth

Code

package DlinkedList;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/3/27 0027  17:04
 * 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
 *
 * 左右两颗子树的深度相差不超过1

 */
public class Problem26 {

    public boolean IsBalanced_Solution(TreeNode root) {

        //root为空直接返回false
        if(root==null){
            return true;
        }

        //左右子树的深度的差大于1的话则返回false
        if((depth(root.left)-depth(root.right)>1)||(depth(root.left)-depth(root.right)<-1)){
            return false;
        }else{
            //判断左右子树,若左右子树深度不大于1 接着判断
           return true&&IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
        }

    }


    //求树的深度
    public int depth(TreeNode root){
        if(root==null) return 0;
        return Math.max(depth(root.left),depth(root.right))+1;
    }




    public static void main(String[] args) {
        TreeNode A = new TreeNode(1);
        TreeNode B= new TreeNode(2);
        TreeNode C= new TreeNode(3);
        TreeNode D= new TreeNode(4);
        TreeNode E= new TreeNode(5);
        TreeNode F= new TreeNode(3);
        TreeNode G= new TreeNode(6);
        TreeNode H= new TreeNode(7);
        TreeNode I= new TreeNode(8);
        A.left=B;
        A.right=C;
        B.left=D;
        B.right=E;
        D.right=H;
        C.left=F;
        C.right=G;
        G.left=I;
        Problem26 problem26 = new Problem26();
        System.out.println(problem26.IsBalanced_Solution(A));

    }


}

Published 223 original articles · won praise 22 · views 20000 +

Guess you like

Origin blog.csdn.net/ZHOUJIAN_TANK/article/details/105146246