4.1 Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.

#include <iostream>
#include <climits>

struct Node
{
    Node *right;
    Node *left;
};
    
class Solution
{
    void helper(Node* n, int depth, int& min, int& max)
    {
        if (n->left == NULL && n->right == NULL)
        {
            if (depth < min) min = depth;
            if (depth > max) max = depth;
            return;
        }
        
        if (n->left != NULL)
        {
            helper(n->left, depth + 1, min, max);
        }
        
        if (n->right != NULL)
        {
            helper(n->right, depth + 1, min, max);
        }
    }
    
public:
    
    bool isBalance(Node* root)
    {
        /*min and max are two "GLOBAL" vars, while depth is local*/
        int min = INT_MAX, max = INT_MIN;
        helper(root, 0, min, max);
        return (max - min > 1) ? 0 : 1;
    }
};

int main()
{
    Node nnode[5];
/*
When writing in C-style, nerver forget to
explicitly initialize structs members or array members.
Or use Class or Stl containers instead.
*/
    for(int i = 0; i < 5; ++i)
    {
        nnode[i].left = NULL;
        nnode[i].right = NULL;
    }
    nnode[0].left = &nnode[1];
    nnode[0].right = &nnode[2];
    nnode[1].left = &nnode[3];
    nnode[3].right = &nnode[4];
    Solution S;
    std::cout << S.isBalance(nnode) << std::endl;
    return 0;
}

Leave a comment