查找二叉搜索树的第K小节点
利用bst的中序遍历的性质
bst 中序遍历可以得到一个有序数组, 每次从stack中弹出一个元素,看k-- ,进行计数即可
Inorder Traversal
We can inorder traverse the tree and get the kth smallest element. Time is O(n).
solution1 中序遍历非递归写法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
//利用二叉树的层次遍历,中间层次是有序数组的情况
Stack<TreeNode> stack =new Stack<>();
TreeNode p =root;
while(p!=null|| !stack.isEmpty())
{
//这里使用while
while(p!=null){
stack.push(p);
p=p.left;
}
//这里使用if 判断即可
if(!stack.isEmpty()){
p = stack.pop();
--k;
if(k==0)
return p.val;
p = p.right;
}
}
return -1;
}
}
c++代码
/**
* 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) {
TreeNode * p =root;
stack<TreeNode *>s ;
while(p!=nullptr || !s.empty() ){
while(p!=nullptr){
s.push(p);
p = p->left;
}
if(!s.empty())
{
//注意在这里面的不同点,是不一样的情况
p= s.top();
s.pop();
k--;
if(k==0)
return p->val;
p=p->right;
}
}
}
};
时间复杂度分析
O(N)
solution2 Binary Search
利用二叉树搜索的性质,可以减少到O(log(N));时间
利用二叉树的性质做出
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
int n = count(root.left);
if (k <= n) {
return kthSmallest(root.left, k);
}
else if(k>n+1){
return kthSmallest(root.right, k-n-1);
}
return root.val;
}
private int count(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + count(root.left)+ count(root.right);
}
}
时间复杂度分析
// O(N * lg N) average runtime and O(N^2) for worst case;
// The best performance is we just have to count the nodes for once (i.e. kth is root), which is O(n);
// the average case when we need count nodes for each subtree traversal, binary search is always log(n), and number of traversed subtrees could be n, then as total is O(nlog(n)).
// worst case complexity should be O(n^2). if the tree is not balanced, it can become a linked list with the largest value at root and to the leaf node in decreasing order. And imagine we want k = 1 in this case.