Advertisement
Guest User

Grokking#198

a guest
Nov 28th, 2021
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 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.  
  15. // Level cua tree dc danh so tu 0
  16. int depth(TreeNode* root) {
  17. int d = 0;
  18. while (root->left != nullptr) {
  19. d += 1;
  20. root = root->left;
  21. }
  22. return d;
  23. }
  24.  
  25. // Return true if node idx at last level exist
  26. // O(d) time complexity
  27. bool exist(int idx, int d, TreeNode* root) {
  28. int left = 0, right = pow(2,d) -1;
  29. int pivot;
  30. for (int i = 0; i < d; ++i) {
  31. pivot = left + (right -left) /2;
  32. if( idx <= pivot) {
  33. root = root->left;
  34. right = pivot;
  35. } else {
  36. root = root->right;
  37. left = pivot;
  38. }
  39. }
  40. return root != nullptr;
  41. }
  42.  
  43. int countNodes(TreeNode* root) {
  44. if (root == nullptr) return 0;
  45.  
  46. int d = depth(root);
  47. if (d == 0) return 1;
  48.  
  49. int left = 1, right = pow(2, d) -1; // Node 0 luon ton tai nen ta danh so left bat dau tu 1
  50. int pivot;
  51. while (left <= right) {
  52. pivot = left + (right - left)/2;
  53. if (exist(pivot, d, root)) left = pivot + 1;
  54. else right = pivot -1;
  55. }
  56.  
  57. return pow(2, d) - 1 + left;
  58. }
  59. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement