1. 程式人生 > 其它 >二叉樹是否為平衡二叉樹

二叉樹是否為平衡二叉樹

連結
平衡二叉樹的性質為: 要麼是一棵空樹,要麼任何一個節點的左右子樹高度差的絕對值不超過 1。給定一棵二叉樹,判斷這棵二叉樹是否為平衡二叉樹。
一顆樹的高度指的是樹的根節點到所有節點的距離中的最大值。

import java.util.Scanner;

public class Main {


    private static Info solve(Node root) {
        if (root == null) {
            return new Info(0, true);
        }
        Info left = solve(root.left);
        Info right = solve(root.right);
        int deep = Math.max(left.deep, right.deep) + 1;
        boolean isBalance = left.isBalance && right.isBalance && Math.abs(left.deep - right.deep) <= 1;
        return new Info(deep, isBalance);
    }


    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        while (in.hasNext()) {
            int n = in.nextInt();
            Node[] nodes = new Node[n + 1];
            for (int i = 1; i <= n; ++i) {
                nodes[i] = new Node(i);
            }
            Node root = nodes[in.nextInt()];
            for (int i = 1; i <= n; ++i) {
                int fa = in.nextInt();
                nodes[fa].left = nodes[in.nextInt()];
                nodes[fa].right = nodes[in.nextInt()];
            }
            Info ret = solve(root);
            System.out.println(ret.isBalance);
        }
    }
}

class Info {
    int deep;
    boolean isBalance;

    public Info(int deep, boolean isBalance) {
        this.deep = deep;
        this.isBalance = isBalance;
    }
}

class Node {
    Node left;
    Node right;
    int val;

    public Node(int val) {
        this.val = val;
    }
}
心之所向,素履以往 生如逆旅,一葦以航