Leetcode 222 Solution

This article provides solution to leetcode question 222 (count-complete-tree-nodes)

https://leetcode.com/problems/count-complete-tree-nodes

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root == NULL)
            return 0;

        int hl = 0;
        int hr = 0;

        TreeNode* l = root;
        TreeNode* r = root;

        while (l) l = l->left, hl++;
        while (r) r = r->right, hr++;

        if (hl == hr)
            return pow(2, hl) - 1;

        return countNodes(root->left) + countNodes(root->right) + 1;
    }
};