jain12

kth smallest element in a BST

Jun 5th, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. class Solution {
  2. public:
  3.   // first method
  4.    int kthSmallest(TreeNode* root, int k) {
  5.       int count = countNodes(root->left);
  6.       if (k <= count) {
  7.           return kthSmallest(root->left, k);
  8.           }
  9.       else
  10.           if (k > count + 1) {
  11.             return kthSmallest(root->right, k-1-count);
  12.             }
  13.       return root->val;
  14.       }
  15.  
  16.   int countNodes(TreeNode* Node) {
  17.       if (Node == NULL)
  18.         return 0;
  19.       return 1 + countNodes(Node->left) + countNodes(Node->right);
  20.       }
  21.  
  22.   // second method
  23.    /*
  24.    int kthSmallest(TreeNode* root, int k) {
  25.       stack<TreeNode *> s;
  26.       queue<int>q;
  27.       int res;
  28.       TreeNode *curr = root;
  29.       while (curr != NULL || s.empty() == false)  {
  30.          while (curr !=  NULL) {
  31.             s.push(curr);
  32.             curr = curr->left;
  33.             }
  34.          curr = s.top();
  35.          s.pop();
  36.          q.push(curr->val );
  37.          curr = curr->right;
  38.          }
  39.      while(k>0){
  40.        res=q.front();
  41.        q.pop();
  42.        k--;
  43.        }
  44.     return res;
  45.     }
  46.     */
  47. };
Add Comment
Please, Sign In to add comment