剑指offer算法题
树
题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。
题目分析
由于给定的是一颗二叉搜索树,而对于二叉搜索树来说,其中序遍历的结果就是该树升序排序后的结果。所以我们可以对该树进行中序遍历,然后找到第k个即可。
方法一 递归
下面是Java代码
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
//设置两个全局变量,一个用于计数,一个用于存储找到的节点。
private int i =0;
private TreeNode node = null;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot == null){
return null;
}
if(k <=0){
return null;
}
KthNode(pRoot.left,k);
i++;
if(i == k){
node = pRoot;
}
KthNode(pRoot.right,k);
return node;
}
}
方法二 非递归
下面是Java代码
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.Stack;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot == null){
return null;
}
if(k <=0){
return null;
}
Stack<TreeNode> s = new Stack<>();
int count = 0;
while(!s.isEmpty()||pRoot!=null){
if(pRoot!=null){
s.push(pRoot); //直接压栈
pRoot = pRoot.left;
}else{
TreeNode node = s.pop(); //出栈并访问
if(++count == k){
return node;
}
pRoot = node.right;
}
}
return null;
}
}