Leetcode 110. Balanced Binary Tree
Leetcode Problem 110: Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
A height-balanced binary tree is defined as:
To determine whether a binary tree is height-balanced:
We will modify the height computation to also return a special value (e.g., -1) if it finds an unbalanced subtree. This helps us avoid redundant computations.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
return checkHeight(root) != -1;
}
private int checkHeight(TreeNode node) {
if (node == null) {
return 0;
}
int leftHeight = checkHeight(node.left);
if (leftHeight == -1) {
return -1;
}
int rightHeight = checkHeight(node.right);
if (rightHeight == -1) {
return -1;
}
if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return Math.max(leftHeight, rightHeight) + 1;
}
}
The time complexity of this solution is O(n), where n is the number of nodes in the tree. This is because in the worst case, we visit each node once and perform a constant amount of work at each node.
The space complexity is O(h) due to the recursion stack, where h is the height of the tree.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?