Given a binary tree, determine if it is height-balanced. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
LeetCode-110: Given a binary tree, determine if it is height-balanced. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
Based on the definition of a height balanced binary tree, following is a high level approach to solve this problem:
Following is a java implementation of the above mentioned approach:
private int maxHeightDifference = Integer.MIN_VALUE;
public boolean isBalanced(TreeNode root) {
if(null == root){
return true;
}
calculateHeightDifferenceViaDFS(root);
return maxHeightDifference <= 1;
}
private int calculateHeightDifferenceViaDFS(TreeNode root){
if(null == root){
return 0;
}
int left = calculateHeightDifference(root.left);
int right = calculateHeightDifference(root.right);
maxHeightDifference = Math.max(maxHeightDifference, Math.abs(left-right));
return 1 + Math.max(left, right);
}
As each node of the tree is processed once, the overall complexity of this algorithm is \(O(n)\) where \(n\) is the number of nodes in the tree.
Be notified of new posts. Subscribe to the RSS feed.