55-Balanced Binary Tree-python

Topic: Enter the root node of a binary tree to determine whether the tree is a balanced binary tree. If the depth of the left and right subtrees of any node in a binary tree does not differ by more than 1, then it is a balanced binary tree.

def tree_depth(root):
    if not root:
        return 0
    left = tree_depth(root.left)
    right = tree_depth(root.right)

    if left>right:
        return left+1
    else:
        return right+1

def is_balanced(root):
    if not root:
        return True
    left = tree_depth(root.left)
    right = tree_depth(root.right)
    diff = left-right
    if diff>1 or diff<-1:
        return False
    return is_balanced(root.left) and is_balanced(root.right)

  Note: Find the depth of the left and right subtrees, and then find the difference to determine whether the difference is correct or not and the balance condition. Traverse all the way to the leaf nodes, and return False if any of the nodes is unbalanced.

Guess you like

Origin blog.csdn.net/wh672843916/article/details/105503758