# 230.cpp

Jul 29th, 2021
618
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
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.     int ans;
14. public:
15.     int kthSmallest(TreeNode* root, int &k) {
16.         if (!root) {
17.             return INT_MIN;
18.         }
19.
20.         ans = kthSmallest(root->left, k);
21.         if (ans != INT_MIN) {
22.             return ans;
23.         }
24.
25.         k--;
26.         if (k == 0) {
27.             return root->val;
28.         }
29.
30.         ans = kthSmallest(root->right, k);
31.
32.         return ans;
33.     }
34. };
RAW Paste Data