```
int kthSmallest(struct TreeNode* root, int k) {
int count = 0; // count the kth elem
struct TreeNode *cur = root, *tmp = NULL;
while(cur){
if(!cur->left){
if(++count == k) return cur->val;
cur = cur->right;
}
else{
tmp = cur->left;
while(tmp->right && tmp->right != cur) tmp = tmp->right;
if(tmp->right == NULL){
tmp->right = cur;
cur = cur->left;
}
else{
tmp->right = NULL;
if(++count == k) return cur->val;
cur = cur->right;
}
}
}
```

}