Taking a binary tree as an input, provide a function to return True if the tree is balanced. The height of a balanced binary tree is defined to be any tree where every node's pair of subtrees do not differ in height by more than 1.
Write your answer as pseudocode to fit into the following:
class Node {
def __init__(self, val, left=None, right=None) {
self.val = val
self.left = left
self.right = right
}
}
def is_balanced(tree) {
# YOUR ANSWER HERE
}
# EXAMPLE 1
1
2 3
4
balanced[4] = Node(4)
balanced[3] = Node(3, balanced[4])
balanced[2] = Node(2)
balanced[1] = Node(1, balanced[2], balanced[3])
print(is_balanced(balanced[1]))
# TRUE
# EXAMPLE 2
1
2
3
unbalanced[3] = Node(3)
unbalanced[2] = Node(2, unbalanced[3])
unbalanced[1] = Node(1, unbalanced[2])
print(is_balanced(unbalanced[1]))
# FALSE