Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- // first method
- int kthSmallest(TreeNode* root, int k) {
- int count = countNodes(root->left);
- if (k <= count) {
- return kthSmallest(root->left, k);
- }
- else
- if (k > count + 1) {
- return kthSmallest(root->right, k-1-count);
- }
- return root->val;
- }
- int countNodes(TreeNode* Node) {
- if (Node == NULL)
- return 0;
- return 1 + countNodes(Node->left) + countNodes(Node->right);
- }
- // second method
- /*
- int kthSmallest(TreeNode* root, int k) {
- stack<TreeNode *> s;
- queue<int>q;
- int res;
- TreeNode *curr = root;
- while (curr != NULL || s.empty() == false) {
- while (curr != NULL) {
- s.push(curr);
- curr = curr->left;
- }
- curr = s.top();
- s.pop();
- q.push(curr->val );
- curr = curr->right;
- }
- while(k>0){
- res=q.front();
- q.pop();
- k--;
- }
- return res;
- }
- */
- };
Add Comment
Please, Sign In to add comment