leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0222.cpp (715B)


      1 class Solution {
      2   public:
      3     int countNodes(TreeNode *root) {
      4         if (!root) return 0;
      5 
      6         int height = 0;
      7         queue<TreeNode *> q;
      8         q.push(root);
      9         while (!q.empty()) {
     10             TreeNode *root = q.front();
     11             q.pop();
     12             int rh = 0, lh = 0;
     13             for (TreeNode *t = root; t; t = t->left)
     14                 lh++;
     15             for (TreeNode *t = root; t; t = t->right)
     16                 rh++;
     17             if (lh == rh)
     18                 height += exp2(rh) - 1;
     19             else {
     20                 height++;
     21                 if (root->left) q.push(root->left);
     22                 if (root->right) q.push(root->right);
     23             }
     24         }
     25         return height;
     26     }
     27 };