题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
分析
对二叉搜索树进行中序遍历,在中间打印节点的时候进行累加判断,第k个被打印出来的节点即所求。
递归版:
public class Solution {
int count=0;
TreeNode resNode;//在每次递归中一直变化的数值,可以定义为全局变量(比较省事),否则就传参
TreeNode KthNode(TreeNode pRoot, int k)
{ core(pRoot,k);
return resNode;
}
//单独写一个函数递归出于两个考虑:
//1.主函数负责处理递归之外的特殊情况
//2.递归体的参数跟主函数不一样
//3.递归体的出口一般在内部,所以如果递归体不是void而是return某个类型的话,会缺少返回语句
public void core(TreeNode node, int k){
if (node==null || count>k) {
return;
}
core(node.left, k);
count++;
if (count == k) {
resNode = node; //只有count == k的时候才去存储节点
}
core(node.right, k);
}
}
非递归版:
import java.util.Stack;
public class Solution {
int count=0;
TreeNode resNode;
TreeNode KthNode(TreeNode pRoot, int k)
{ core(pRoot,k);
return resNode;
}
public void core(TreeNode node, int k){
if (node==null || count>k) {
return;
}
Stack<TreeNode> stack=new Stack<TreeNode>();
while(node!=null||!stack.isEmpty()){
if(node!=null){
stack.push(node);
node=node.left;
}
else{
node=stack.pop();
count++;
if(count==k){
resNode=node;
}
node=node.right;
}
}
}
}