173 判断二叉树是否为平衡二叉树
Table of Contents

ac

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

class TreeNode{
    TreeNode left;
    TreeNode right;
    int val;

    public TreeNode(int val) {
        this.val = val;
        left = null;
        right = null;
    }
}

class Rs{
    boolean isBalance;
    int height;

    public Rs(boolean isBalance, int height) {
        this.isBalance = isBalance;
        this.height = height;
    }
}

public class Main {
    public static Scanner sc = new Scanner(System.in);

    public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    public static long mod = (long) Math.pow(2, 29);

    public static void main(String[] args) throws Exception {
        String line;
        String[] strArr;
        line = reader.readLine();
        strArr = line.split(" ");
        int n = Integer.valueOf(strArr[0]);
        int rootVal = Integer.valueOf(strArr[1]);
        Map<Integer, TreeNode> mp = new HashMap<>(n);
        for (int i = 0; i < n; i++) {
            line = reader.readLine();
            strArr = line.split(" ");
            int val = Integer.valueOf(strArr[0]);
            int leftVal = Integer.valueOf(strArr[1]);
            int rightVal = Integer.valueOf(strArr[2]);

            if (!mp.containsKey(val)) {
                mp.put(val, new TreeNode(val));
            }
            if (leftVal != 0) {
                if (!mp.containsKey(leftVal)) {
                    mp.put(leftVal, new TreeNode(leftVal));
                }
                mp.get(val).left = mp.get(leftVal);
            }
            if (rightVal != 0) {
                if (!mp.containsKey(rightVal)) {
                    mp.put(rightVal, new TreeNode(rightVal));
                }
                mp.get(val).right = mp.get(rightVal);
            }
        }
        TreeNode root = mp.get(rootVal);
        Rs rs = isBalanceTree(root);
        System.out.println(rs.isBalance ? "true": "false");
    }

    // 一次递归,既可以求出高度,也可以判断是否是平衡二叉树
    static Rs isBalanceTree(TreeNode root){
        if(root == null){
            return new Rs(true, 0);
        }
        if(root.left == null && root.right == null){
            return new Rs(true, 1);
        }
        Rs leftRs = isBalanceTree(root.left);
        Rs rightRs = isBalanceTree(root.right);
        boolean balance = leftRs.isBalance && rightRs.isBalance && Math.abs(leftRs.height-rightRs.height) <= 1;
        int height = Math.max(leftRs.height, rightRs.height) + 1;
        return new Rs(balance, height);
    }

}
/*
9 1
1 2 3
2 4 5
4 0 8
8 0 0
5 9 0
9 0 0
3 6 7
6 0 0
7 0 0

true
 */