目录
1.题目描述
2.递归实现
/**
* 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;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return (Math.abs(left-right)<2)&&isBalanced(root.left)&&isBalanced(root.right);
}
public static int maxDepth(TreeNode root){
if(root == null){
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return (left>right?left:right)+1;
}
}
3.迭代实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class IsBalance{
public int height;
public boolean balance;
}
class Solution {
public static IsBalance function(TreeNode root){
IsBalance res = new IsBalance();
res.height = 0;
res.balance = true;
if(root == null){
return res;
}
IsBalance lres = new IsBalance();
lres = function(root.left);
if(lres.balance==false){
return lres;
}
IsBalance rres = new IsBalance();
rres = function(root.right);
if(rres.balance==false){
return rres;
}
res.height = (lres.height>rres.height)?lres.height+1:rres.height+1;
res.balance = Math.abs(lres.height-rres.height)<2;
return res;
}
public boolean isBalanced(TreeNode root) {
return function(root).balance;
}
}