110.判断是否是平衡二叉树[简单]

221 阅读1分钟

题目

判断是否是平衡二叉树

平衡二叉树是指左右子树的高度差不超过1。

解法一

思路

需要先求得二叉树的高度。

二叉树的左右子树可能高度不同,应该以子树高的那个作为树的高度。

代码

public int depth(TreeNode root) {
  if (root == null) {
    return 0;
  }
  int left = depth(root.left);
  int right = depth(root.right);
  return Math.max(left, right) + 1;
}

平衡二叉树的判断:左右子树的高度差

public boolean isBalance(TreeNode root) {
  if (root == null) {
    return true;
  }
  int left = depth(root.left);
  int right = depth(root.right);
  if (Math.abs(left - right) > 1) {
    return false;
  }
  return isBalance(root.left) && isBalance(root.right);
}

update20220513

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int left = depth(root.left);
        int right = depth(root.right);
        if (Math.abs(left - right) > 1) {
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }

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

解法二

思路

上面的实现可能会对下面的节点访问多次。

需要后序遍历。

代码

public boolean isBalance(TreeNode root) {
  return depth(root) >= 0;
}

public int depth(TreeNode root) {
  if (root == null) {
    return 0;
  }
  int left = depth(root.left);
  int right = depth(root.right);
  if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
    return -1;
  }
  return Math.max(left, right) + 1;
}

硬广告

欢迎关注公众号:double6