LeetCode: Balanced Binary Tree Solution

Modified version of "Maximum Depth of Binary Tree"

Approach

During the calculation of tree height, check the different in height between two subtrees

Implementation

1var isBalanced = function (root) {
2 let res = true
3
4 const recursion = node => {
5 if (!node) return 0
6
7 const leftHeight = recursion(node.left)
8 const rightHeight = recursion(node.right)
9
10 res &&= Math.abs(leftHeight - rightHeight) <= 1
11
12 return Math.max(leftHeight, rightHeight) + 1
13 }
14
15 recursion(root)
16
17 return res
18}

References

Original problem

Similar problems

Maximum Depth of Binary Tree

Comments

Loading comments...

Tags

leetcode

recursion

tree

binary tree

dfs

Next Post

LeetCode: Maximum Depth of Binary Tree

Sep 3, 2022

Explanation is hard

Previous Post

LeetCode: Invert Binary Tree

Sep 2, 2022

A Broken Interview: The Origin

HoningJS

Search Posts