Accepted C++ solution


  • 0
    V
    class Solution {
    public:
        int countNodes(TreeNode* root) {
            int totCount=0;
            int count=0;
            int initHeight = 0, height = 0;
            TreeNode *iter = root;
            initHeight = getHeight(root);
            height = initHeight;
            while(iter != NULL && height >= 0) {
                if(checkHeight(iter, height, true) == true) {
                    if(height > 0) {
                        count += pow(2, height-1);
                    } else {
                        count += 1;
                    }
                    iter = iter->right;
                } else {
                    iter = iter->left;
                }
                height -= 1;
            }
            totCount = count + pow(2, initHeight) - 1;
            return(totCount);
        }
        
        bool checkHeight(TreeNode *n, int height, bool init) {
            if(n == NULL) return false;
            if(height == 0) return true;
            if(init == true) {
                return(checkHeight(n->left, height-1, false));
            }
            return(checkHeight(n->right, height-1, false));
        }
        
        int getHeight(TreeNode *root) {
            if(root == NULL) return -1;
            return(getHeight(root->left) + 1);
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.