Posts Balanced Binary Tree
Post
Cancel

Balanced Binary Tree

PROBLEM DESCRIPTION

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

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
    public boolean isBalanced(TreeNode root) {

        if(root == null) return true;
        
        int l = depth(root.left);
        int r = depth(root.right);

        int diff = Math.abs(l-r);

        return diff<=1 && isBalanced(root.left) && isBalanced(root.right);

    }

    public int depth(TreeNode root){

        if(root == null) return 0;

        int l = depth(root.left);
        int r = depth(root.right);

        return 1 + Math.max(l,r);

    }

}
This post is licensed under CC BY 4.0 by the author.