这道题中的平衡二叉树的定义是:二叉树的每个节点的左右子树的高度差的绝对值不超过 1,则二叉树是平衡二叉树。根据定义,一棵二叉树是平衡二叉树,当且仅当其所有子树也都是平衡二叉树,因此可以使用递归的方式判断二叉树是不是平衡二叉树,递归的顺序可以是自顶向下或者自底向上。

自顶向下的递归 (先序遍历:处理在递归调用左右子树之前)

定义函数 height,用于计算二叉树中的任意一个节点 p 的高度:
110. 平衡二叉树 - 图1
有了计算节点高度的函数,即可判断二叉树是否平衡。具体做法类似于二叉树的前序遍历,即对于当前遍历到的节点,首先计算左右子树的高度,如果左右子树的高度差是否不超过 1,再分别递归地遍历左右子节点,并判断左子树和右子树是否平衡。这是一个自顶向下的递归的过程

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public boolean isBalanced(TreeNode root) {
  18. if (root == null) {
  19. return true;
  20. }
  21. return Math.abs(height(root.left) - height(root.right)) <= 1 &&
  22. isBalanced(root.left) && isBalanced(root.right);
  23. }
  24. public int height(TreeNode root) {
  25. if (root == null) {
  26. return 0;
  27. }
  28. return Math.max(height(root.left), height(root.right)) + 1;
  29. }
  30. }

自底向上的递归(后续遍历:递归调用左右子树之后再处理)

由于是自顶向下递归,因此对于同一个节点,函数 height 会被重复调用,导致时间复杂度较高。如果使用自底向上的做法,则对于每个节点,函数 height 只会被调用一次。
自底向上递归的做法类似于后序遍历,对于当前遍历到的节点,先递归地判断其左右子树是否平衡,再判断以当前节点为根的子树是否平衡。如果一棵子树是平衡的,则返回其高度(高度一定是非负整数),否则返回 -1。如果存在一棵子树不平衡,则整个二叉树一定不平衡。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public boolean isBalanced(TreeNode root) {
  18. return height(root) >= 0;
  19. }
  20. public int height(TreeNode root) {
  21. if (root == null) {
  22. return 0;
  23. }
  24. int leftHeight = height(root.left);
  25. int rightHeight = height(root.right);
  26. if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
  27. return -1;
  28. } else {
  29. return Math.max(leftHeight, rightHeight) + 1;
  30. }
  31. }
  32. }