Decision of Balanced Binary Tree

1. Title

Title Description: Enter the root node of a binary tree to determine if it is a balanced binary tree.If the left and right subtrees of any node in a binary tree have no more than 1 depth difference, it is a balanced binary tree.

2. Solution

2.1 Method 1

Thought: When traversing each node of a tree, call the TreeDepth function to get the depth of its left and right subtrees. If the depth of each node's left and right subtrees do not differ by more than 1, then it is defined as a balanced binary tree.

int TreeDepth(const BinaryTreeNode* pRoot)
{
    if(pRoot == nullptr)
        return 0;

    int nLeft = TreeDepth(pRoot->m_pLeft);
    int nRight = TreeDepth(pRoot->m_pRight);

    return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}

bool IsBalanced_Solution1(const BinaryTreeNode* pRoot)
{
    if(pRoot == nullptr)
        return true;

    int left = TreeDepth(pRoot->m_pLeft);
    int right = TreeDepth(pRoot->m_pRight);
    int diff = left - right;
    if(diff > 1 || diff < -1)
        return false;

    return IsBalanced_Solution1(pRoot->m_pLeft) 
        && IsBalanced_Solution1(pRoot->m_pRight);
}

2.2 Method 2

Idea: If we traverse each node of a binary tree in a postorder, then we have traversed its left and right subtrees before traversing a node. As long as we record the depth of each node when traversing it (the depth of a node equals the length of its path to a leaf node), we can traverse each node to determine if it is notBalanced.

bool IsBalanced_Solution2(const BinaryTreeNode* pRoot)
{
    int depth = 0;
    return IsBalanced(pRoot, &depth);
}

bool IsBalanced(const BinaryTreeNode* pRoot, int* pDepth)
{
    if(pRoot == nullptr)
    {
        *pDepth = 0;
        return true;
    }

    int left, right;
    if(IsBalanced(pRoot->m_pLeft, &left) 
        && IsBalanced(pRoot->m_pRight, &right))
    {
        int diff = left - right;
        if(diff <= 1 && diff >= -1)
        {
            *pDepth = 1 + (left > right ? left : right);
            return true;
        }
    }

    return false;
}

Posted on Fri, 14 Feb 2020 12:31:08 -0500 by undertaker16