https://leetcode-cn.com/problems/balanced-binary-tree/
解一:
/**
* 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) {
if (root == null) {
return true;
}
return isBalanced(root.left) &&
isBalanced(root.right) &&
Math.abs(deepth(root.left) - deepth(root.right)) <= 1;
}
private int deepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(deepth(root.left), deepth(root.right)) + 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) {
if (root == null) {
return true;
}
if (getHeight(root) == -1) {
return false;
}
return true;
}
private int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
int left = getHeight(root.left);
int right = getHeight(root.right);
if (left == -1 || right == -1) {
return -1;
}
if (Math.abs(left - right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}
}
网友评论