My AC C++ solution


  • -10
    Y

    class Solution {
    public:
    int countNodes(TreeNode* root) {
    int res = 0;
    while (root) {
    int lh = 0, rh = 0;
    for (TreeNode* p = root->left; p; p = p->left) ++lh;
    for (TreeNode* p = root->right; p; p = p->left) ++rh;
    res += (lh == rh)?(1 << lh):(1 << rh);
    root = (lh == rh)?root->right:root = root->left;
    }
    return res;
    }
    };


  • 0
    B

    good code! Here is the formatted one.

    class Solution {
        public: 
        int countNodes(TreeNode* root) { 
            int res = 0; 
            while (root) { 
                int lh = 0, rh = 0; 
                for (TreeNode* p = root->left; p; p = p->left) 
                    ++lh; 
                for (TreeNode* p = root->right; p; p = p->left) 
                    ++rh; 
                res += (lh == rh)?(1 << lh):(1 << rh); 
                root = (lh == rh)?root->right:root = root->left; 
            } 
            return res; 
        }
    };

Log in to reply
 

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