剑指offer55 是否是平衡二叉树 Java

荒凉一梦 提交于 2019-11-27 15:40:52
public class IsBalancedTree55 {
    static class Node {
        int val;
        Node left;
        Node right;

        public Node(int val) {
            this.val = val;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "val=" + val +
                    ", left=" + left +
                    ", right=" + right +
                    '}';
        }
    }

    public static void main(String[] args) {
        Node root = new Node(8);
        Node node21 = new Node(6);
        Node node22 = new Node(10);
        Node node31 = new Node(5);
        Node node32 = new Node(7);
        Node node33 = new Node(9);
        Node node34 = new Node(11);
        root.left = node21;
        root.right = node22;
        node21.left = node31;
        node21.right = node32;
        node22.left = node33;
        node22.right = node34;
        System.out.println(isBalanced(root));
    }

    private static boolean isBalanced(Node root) {
        if (root == null)
            return true;
        //root左孩子的树高
        int leftHeight = height(root.left);
        //root右孩子的树高
        int rightHeight = height(root.right);
        //root左右孩子高度差大于1,返回false
        if (Math.abs(rightHeight - leftHeight) > 1) {
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }

    private static int height(Node root) {
        if (root == null)
            return 0;
        int left = height(root.left);
        int right = height(root.right);
        return Math.max(left, right) + 1;
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!