0
点赞
收藏
分享

微信扫一扫

判断是否为平衡二叉树

独孤凌雪 2022-02-06 阅读 39
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 boolean isBalanced(Node head) {
    return process(head).isBalanced;
  }

  public static class ReturnType {
    public boolean isBalanced;
    public int height;

    public ReturnType(boolean isBalanced, int height) {
      this.isBalanced = isBalanced;
      this.height = height;
    }
  }

  public static ReturnType process(Node x) {
    if (x == null)
      return new ReturnType(true, 0);
    ReturnType leftData = process(x.left);
    ReturnType rightData = process(x.right);
    int height = Math.max(leftData.height, rightData.height);
    boolean isBalanced = leftData.isBalanced && rightData.isBalanced &&
                         Math.abs(leftData.height - rightData.height) < 2;
    return new ReturnType(isBalanced, height);
  }
}
举报

相关推荐

0 条评论