您的位置:首页 > 编程语言 > C语言/C++

LeetCode 230. Kth Smallest Element in a BST

2016-08-26 16:29 471 查看
题目链接:https://leetcode.com/problems/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:

What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

Hint:

Try to utilize the property of a BST.
What if you could modify the BST node's structure?
The optimal runtime complexity is O(height of BST).

思路:首先注意是二叉搜索树,是一种特殊的二叉树,性质:每个节点都不比它左子树的任意元素小,而且不比它的右子树的任意元素大。
遍历包括:

前序遍历:根节点->左子树->右子树

中序遍历:左子树->根节点->右子树

后序遍历:左子树->右子树->根节点

我们采用中序遍历的方法,实现方法有两种:非递归和递归,自己写的是非递归的,因为当遍历过根节点之后还要回来,所以必须将其存起来。考虑到后进先出的特点,选用栈存储。数量确定,以顺序栈存储。采用STL库中stack。

参考链接:http://blog.csdn.net/fansongy/article/details/6798278/

代码:

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> s;
TreeNode* p=root;
TreeNode* tmp;
int result;
while(p!=NULL||s.empty()==0)
{
while(p!=NULL)
{
s.push(p);
p=p->left;
}
tmp=s.top();
s.pop();
if(--k!=0)
{
result=tmp->val;
break;
}
p=tmp;
p=p->right;
}
return result;
}
};


还有一种方法是用递归方式实现(by dr),用dfs,一遇到递归就有点晕,设计不好,以后要直面问题,不能回避。。。

class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
int res;
dfs(root, k, res);
return res;
}
void dfs(TreeNode* curNode, int& k, int& res){
if(curNode!=NULL){
dfs(curNode->left, k, res);
if(--k==0)
res = curNode->val;
else
dfs(curNode->right, k, res);
}
}
};


PS:以上方法算法的时间复杂度应该是O(k)关于题目中的hint,当TreeNode中的属性可以扩展时,加一个存储左子树的节点个数,那么搜索时,当k<leftnode 时,在左子树中搜索,k=leftnode时,返回当前节点,否则在右子树中搜索。此时时间复杂度O(BST的高度)

参考链接:http://bookshadow.com/weblog/2015/07/02/leetcode-kth-smallest-element-bst/

后来又写了一遍:

代码:

class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
int re=0;
DFS(root,k,re);
return re;
}
void DFS(TreeNode* root, int& k,int &re)
{
if(root==NULL)
return;
DFS(root->left,k,re);
k--;
if(k==0)
re=root->val;
DFS(root->right,k,re);
return;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode BST