s4553711
4/16/2017 - 3:13 PM

222.cpp

/**
 * 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 left_c = 0, right_c = 0;
        TreeNode* l = root;
        while(l != NULL) {
            l = l->left;
            left_c += 1;
        }
        TreeNode* r = root;
        while(r != NULL) {
            r = r->right;
            right_c += 1;
        }
        if (left_c == right_c) return (1 << left_c) - 1;
        return 1 + countNodes(root->left) + countNodes(root->right);
    }
};