Balanced Binary Tree
Description
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
/**
* 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;
* }
* }
*/
class ResultType{
public boolean isBalanced;
public int maxDepth ;
public ResultType(boolean isBalanced , int maxDepth){
this.isBalanced = isBalanced ;
this.maxDepth = maxDepth ;
}
}
public class Solution {
/**
* @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
return helper(root).isBalanced ;
}
private ResultType helper(TreeNode root){
if(root == null ){
return new ResultType(true , 0) ;
}
ResultType left = helper(root.left);
ResultType right = helper(root.right);
if(! left.isBalanced || ! right.isBalanced){
return new ResultType(false , -1) ;
}
if(Math.abs(left.maxDepth - right.maxDepth) > 1){
return new ResultType(false , -1) ;
}
return new ResultType(true , Math.max(left.maxDepth, right.maxDepth)+1) ;
}
}
本文介绍如何使用递归方法判断给定的二叉树是否为高度平衡树,关键在于比较左右子树的最大深度差,并返回结果。通过 helper 函数实现深度计算和不平衡判断。
201

被折叠的 条评论
为什么被折叠?



