题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思路:(本题考查二叉树的中序遍历)
根据二叉搜索树的特点,经过中序遍历的二叉树就是从小到大排序好的序列,因此我们在对二叉搜索树中序遍历的过程中一边遍历,一边统计遍历的节点数,很容易找到第k个节点。
实现1:递归
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
//递归的方法
int count=0;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot!=null){
TreeNode leftNode=KthNode(pRoot.left,k);
if(leftNode!=null){
return leftNode;
}
count++;
if(count==k){
return pRoot;
}
TreeNode rightNode=KthNode(pRoot.right,k);
if(rightNode!=null){
return rightNode;
}
}
return null;
}
}
实现2:非递归(堆栈)
import java.util.Stack;
public class Solution {
//非递归的方法实现
int count=0;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot==null||k==0){
return null;
}
Stack<TreeNode> s=new Stack<>();
while(pRoot!=null||!s.isEmpty()){
while(pRoot!=null){
s.push(pRoot);
pRoot=pRoot.left;
}
pRoot=s.pop();
count++;
if(count==k){
return pRoot;
}
pRoot=pRoot.right;
}
return null;
}
}