Given a pointer to the root node of a binary tree, return true if the binary tree is height-balanced. A height-balanced binary tree is a Binary tree in which the difference between the left subtree height and the right subtree height is at most 1. Height of a binary tree is the number of edges between the root node to the longest leaf node.
A height balanced
binary tree is nothing but a binary tree where the difference in heights of the left subtree
and right subtree
is atmost 1.
Here, we are going to go at the absolute leaf nodes (at the end of the tree) and return some information from there. We are essentially going to bubble up information in order to determine if the tree is height balanced.
isBalanced
and height
.0
and a leaf node is ALWAYS BALANCED.tuple
or an object of TreeInfo
class that will have isBalanced = true
and height = -1
leftSubtreeInfo
by recursive approach - calling the same function again with tree.left
.rightSubtreeInfo
by recursive approach - calling the same function again with tree.right
.leftBalanced && rightBalanced && absolute(leftHeight - height) <=1
.maximum(leftHeight, rightHeight) + 1
O(n)
- Time complexity because we have to traverse all the nodes of the tree at max.O(h)
- Space complexity.