Advertisement
nikunjsoni

230

May 9th, 2021
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.76 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 kthSmallest(TreeNode* root, int k) {
  15.         stack<TreeNode*> stk;
  16.         while(true){
  17.             while(root){
  18.                 stk.push(root);
  19.                 root = root->left;
  20.             }
  21.             root = stk.top();
  22.             stk.pop();
  23.             if(--k == 0) return root->val;
  24.             root = root->right;
  25.         }
  26.         return NULL;
  27.     }
  28. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement