没有输出的输入是不完整的

0%

剑指offer-二叉搜索树的第k个结点

本文为剑指 offer 系列第五十九篇。
主要知识点为二叉搜索树,二叉搜索树由于本身的特性,其中序遍历结果是有序的,
针对这一点,经常有题目出现。

题目描述

给定一棵二叉搜索树,请找出其中的第k小的结点。
例如(5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。

解题思路

思路1

中序遍历,将遍历的节点数据保存到一个数组中,然后返回数组的第K个节点即可。

思路2

找一个全局计数器表示中序遍历到多少个节点,如果到第K个节点就可以直接返回当前结果了。如果没有到第K个节点,那么就返回NULL。

解题代码

思路1代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{

if(!pRoot || k<=0) return NULL;
inorder(pRoot,res);
if(res.size() < k){
return NULL;
} else{
return res[k-1];
}
}

private:
vector<TreeNode*> res;
void inorder(TreeNode* root,vector<TreeNode*>& res){
if(!root) return ;
if(root->left) inorder(root->left,res);
res.push_back(root);
if(root->right) inorder(root->right,res);
}
};

时间复杂度为O(n),空间复杂度为O(n)

思路2代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{

if(!pRoot || k<=0) return NULL;
inorder(pRoot,k);
return res;
}
int count = 0;
TreeNode* res = NULL;
void inorder(TreeNode* root,int k){
if(!root) return ;
if(root->left) inorder(root->left,k);
count++;
if(count == k){
res = root;
return;
}
if(root->right) inorder(root->right,k);
}
};

时间复杂度为O(n),空间复杂度为O(n)
以上,本题结束!