Advertisement
vaibhav1906

Kth Smallest in bst

Jan 7th, 2022
937
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.47 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     void f(TreeNode* root, int k, int &counter, int &ans){
  4.         if(root==NULL)return;
  5.        
  6.         f(root->left, k, counter,ans);
  7.         counter++;
  8.         if(counter==k){
  9.             ans = root->val;
  10.         }
  11.         f(root->right, k,counter,ans);
  12.        
  13.     }
  14.     int kthSmallest(TreeNode* root, int k) {
  15.         int counter = 0;
  16.         int ans;
  17.         f(root, k, counter, ans);
  18.        
  19.         return ans;
  20.        
  21.     }
  22. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement