110. 平衡二叉树

给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 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. } else {
  21. return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
  22. }
  23. }
  24. public int height(TreeNode root) {
  25. if (root == null) {
  26. return 0;
  27. } else {
  28. return Math.max(height(root.left), height(root.right)) + 1;
  29. }
  30. }
  31. // 作者:LeetCode-Solution
  32. // 链接:https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/
  33. }
  34. }
  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. // 作者:LeetCode-Solution
  33. // 链接:https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/
  34. }