[LeetCode230] Kth Smallest Element in a BST

题目:

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Follow up:

分类:Tree Binary Search

代码:

第一种:需要额外空间,不太好

 1 class Solution {
 2 private:
 3     vector<int> res;
 4 public:
 5     int kthSmallest(TreeNode* root, int k) {
 6         
 7         if(!root)
 8             return 0;
 9         inorder(root);
10         return res[k - 1];
11     }
12     
13     void inorder(TreeNode* root)
14     {
15         if(root)
16         {
17             inorder(root->left);
18             res.push_back(root->val);
19             inorder(root->right);
20         }
21     }
22 };

第二种:

 1 class Solution {
 2 
 3 public:
 4     int kthSmallest(TreeNode* root, int k) {
 5         if(!root)
 6             return 0;
 7         //非递归中序遍历
 8         stack<TreeNode*> stk;
 9         TreeNode* cur = root;
10         while(cur || !stk.empty())
11         {
12             while(cur)
13             {
14                 stk.push(cur);
15                 cur = cur->left;
16             }
17             cur = stk.top();
18             if(--k == 0)
19                 return cur->val;
20             stk.pop();
21             cur = cur->right;
22         }
23         return  0;
24     }
25 };

 

posted @ 2016-08-16 13:03  zhangbaochong  阅读(238)  评论(0编辑  收藏  举报