判断一棵二叉树是否是平衡二叉树

2019-11-27  本文已影响0人  Ramsey16k

思路:
递归方式判断,返回的信息应该有两个:
(1)这棵树是否是平衡的
(2)这棵树的高度为多少

public class IsBalancedTree{
    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    public static class ReturnData {
        public boolean isB; // 是否平衡
        public int h; // 高度

        public ReturnData(boolean isB, int h) {
            this.isB = isB;
            this.h = h;
        }
    }

    public static ReturnData process(Node head) {
        if (head == null) { // 空树是平衡的
            return new ReturnData(true, 0);
        }
        ReturnData leftData = process(head.left);
        if (!leftData.isB) { // 左子树不平衡,返回false
            return new ReturnData(false, 0);
        }
        ReturnData rightData = process(head.right);
        if (!rightData.isB) { // 右子树不平衡,返回false
            return new ReturnData(false, 0);
        }
        if (Math.abs(leftData.h - rightData.h) > 1) {
            //左子树和右子树的高度查大于1,返回false
            return new ReturnData(false, 0);
        }
        //节点的高度 = 左子树和右子树中较大的那个高度 + 1
        return new ReturnData(true, Math.max(leftData.h, rightData.h) + 1);
    }

    public static boolean isB(Node head){
        // 判断是否是平衡二叉树
        return process(head).isB;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(6);
        head.right.right = new Node(7);

        System.out.println(isB(head));
    }
}
上一篇下一篇

猜你喜欢

热点阅读