文章目录
- 题目描述
- 思路 && 代码
- 二刷
一脸懵逼,居然没写这道题的题解。。
题目描述
思路 && 代码
- 思路:平衡二叉树判断公式 = 左子树满足 + 右子树满足 + 左右子树高度差不超过1
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {public boolean isBalanced(TreeNode root) {return isBalancedTree(root) != -1;}// 为平衡二叉树,返回深度;否则返回-1int isBalancedTree(TreeNode root){// 空为平衡二叉树if(root == null){return 0;}int left = isBalancedTree(root.left);int right = isBalancedTree(root.right);// 左子树不是 || 右子树不是 || 左右子树不平衡if(left == -1 || right == -1 || left - right < -1 || left - right > 1){return -1;}return Math.max(left, right) + 1;}
}
- 无注释版本
class Solution {public boolean isBalanced(TreeNode root) {return isBalancedTree(root) != -1; }public int isBalancedTree(TreeNode root) {if(root == null) {return 0;}int left = isBalancedTree(root.left);int right = isBalancedTree(root.right);if(left - right > 1 || left - right < -1 || left == -1 || right == -1) {return -1;}return Math.max(left, right) + 1;}
}
二刷
- 好家伙,写出了不一样的写法
class Solution {public boolean isBalanced(TreeNode root) {if(root == null) {return true;}if(isBalanced(root.left) && isBalanced(root.right)) {int left = isBalancedTree(root.left);int right = isBalancedTree(root.right);int diff = left - right;return diff < 2 && diff > -2;}return false;}int isBalancedTree(TreeNode root) {if(root == null) {return 0;}return Math.max(isBalancedTree(root.left), isBalancedTree(root.right)) + 1;}
}
- 还是这个简洁点哇
class Solution {public boolean isBalanced(TreeNode root) {return isBalancedTree(root) != -1;}int isBalancedTree(TreeNode root) {if(root == null) {return 0;}int left = isBalancedTree(root.left);int right = isBalancedTree(root.right);if(right - left > 1 || right - left < -1 || left == -1 || right == -1) {return -1;}return Math.max(left, right) + 1;}
}