Advertisement
nikunjsoni

222-1

May 5th, 2021
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. public:
  14.     int countNodes(TreeNode* root) {
  15.         if(!root) return 0;
  16.         int depth = getDepth(root);
  17.         int left = 1, right = pow(2, depth)-1, mid;
  18.         while(left <= right){
  19.             mid = (left+right)>>1;
  20.             if(check(mid, depth, root))
  21.                 left = mid+1;
  22.             else
  23.                 right = mid-1;
  24.         }
  25.         return pow(2, depth) - 1 + left;
  26.     }
  27.    
  28.     int getDepth(TreeNode *root){
  29.         int depth = 0;
  30.         while(root->left){
  31.             depth++;
  32.             root = root->left;
  33.         }
  34.         return depth;
  35.     }
  36.    
  37.     bool check(int idx, int depth, TreeNode *root){
  38.         int left = 0, right = pow(2, depth)-1, mid;
  39.         for(int i=0; i<depth; i++){
  40.             mid = (left+right)>>1;
  41.             if(idx <= mid){
  42.                 root = root->left;
  43.                 right = mid;
  44.             }
  45.             else{
  46.                 root = root->right;
  47.                 left = mid+1;
  48.             }
  49.         }
  50.         return root != NULL;
  51.     }
  52.    
  53. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement