/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
class ResultType {
boolean isB = true;
int height;
}
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
public boolean isBalanced(TreeNode root) {
// write your code here
if(root == null) return true;
return helper(root).isB;
}
public ResultType helper(TreeNode root) {
ResultType result = new ResultType();
if(root == null) {
//result.isB = true;
result.height = 0;
return result;
}
ResultType left = helper(root.left);
ResultType right = helper(root.right);
if(!left.isB || !right.isB) {
result.isB = false;
return result;
}
if(Math.abs(left.height - right.height) > 1) {
result.isB = false;
return result;
}
result.height = Math.max(left.height, right.height) + 1;
return result;
}
}
Check Balanced java 走地牙CTCI 4.4
最新推荐文章于 2019-04-14 03:48:06 发布