MrainW's Home

All things come to those who wait!

0%

LeetCode 110. Balanced Binary Tree

Question

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 left and right subtrees of every node differ in height by no more than 1.

https://leetcode.com/problems/balanced-binary-tree/

Solution

  • Solution1 – DFS, bottom up
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}

private int getHeight(TreeNode node) {
if (node == null)
return 0;
int lh = getHeight(node.left), rh = getHeight(node.right);
if (lh == -1 || rh == -1 || Math.abs(lh - rh) > 1)
return -1;
return 1 + Math.max(lh, rh);
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels