[Offer] [55-2] [] balanced binary tree

Title Description

  Input binary tree root node, the tree determination is not a balanced binary tree. If the depth of a binary tree left any node in the right subtree differ by no more than 1, then it is a balanced binary tree. For example, in FIG binary tree is a balanced binary tree.

Cattle brush off questions address network

Ideas analysis

  Determining a height difference between the left and right subtrees in depth during the binary tree, if the height difference is greater than 1, it returns -1, description is not a balanced binary tree, a binary tree of depth otherwise.

Test Case

  1. Functional test: balancing binary tree; not a balanced binary tree; all the nodes in the binary tree are no left / right subtree.
  2. Special input test: only one node in the binary tree; nullptr head node pointer of the binary tree.

Java code

public class Offer055_02 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();
        
    }

    public static  boolean IsBalanced_Solution(TreeNode root) {
        return Solution1(root);
    }

    private static boolean Solution1(TreeNode root) {
        return getDepth(root)!=-1;
    }
    
    private static int  getDepth(TreeNode root) {
        if(root==null) return 0;
        int leftDep = getDepth(root.left);
        if(leftDep == -1) return -1;
        int rightDep = getDepth(root.right);
        if(rightDep==-1) return -1;
        return Math.abs(leftDep-rightDep) >1 ? -1 :(Math.max(leftDep,rightDep) + 1);
    }

    private static void test1() {

    }

    private static void test2() {

    }
    private static void test3() {

    }

}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer552-ping-heng-er-cha-shu.html