您的位置:首页 > 其它

[leetcode 230]Kth Smallest Element in a BST----求二叉搜索树的第K小值

2016-03-09 21:51 417 查看
Question:

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.
分析:

题目是给定一个二叉搜索树,求写一个函数找到这个二叉搜索树的第K小的元素值。

1、暴力法:

对二叉搜索树进行中序遍历,并将结果存在vector中,则vector[k-1]即为所求。

2、计数法:

根据二叉搜索树的特点可以知道,根节点左边都是比根节点小的值,根节点右边的值都是比根节点大的,所以也是中序遍历,只不过不存储遍历结果,只统计访问过的节点次数。这样,当访问第k个节点时候,第k个节点的元素值即为所求。

代码如下:

<span style="font-size:14px;">/**
* 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 t;
int r;
int count;
public:
int kthSmallest(TreeNode* root, int k) {
t = k;
count = 0;
Inorder(root);
return r;
}

void Inorder(TreeNode* root){
if(root->left != NULL){
Inorder(root->left);
}
++count;
if(count == t){
r = root->val;
return ;
}

if(root->right != NULL){
Inorder(root->right);
}
}
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: