给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
int index;//全局变量 默认为0
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot!=null){
if(pRoot==null)
return null;
TreeNode node=KthNode(pRoot.left,k);
if(node!=null)
return node;
if(++index==k)
return pRoot;
TreeNode node2=KthNode(pRoot.right,k);
if(node2!=null)
return node2;
}
return null;
}
}
/*
TreeNode node = KthNode(root.left,k);这个node是接收左子树返回的值的,如果node不为null,
就说明已经在左子树中找到了这个值,就返回node,递归结束。如果左子树为null,就继续添加数,判断。
比如说 5 / \ 3 7 /\ /\ 2 4 6 8,递归最下面的一层为KthNode(3,1),{node=kthNode(3.left,1),
index++,node=kthNode(3.right,1)}==》(null,加入3,null)==》加入3时index++,所以index==k,
于是返回node=3给KthNode(3,1),然后KthNode(3,1)判断出它的子过程返回了一个值,说明已经找到一个数了,
于是将这个返回,如果子过程没有返回node就说明左子树中没有找到,然后index++,又判断是否等于k,
若不等于,然后KthNode(6,1),判断这个子过程有没有返回node,依次往上递归
*/
第二种方法:
本质还是中序遍历,只不过这个方法是把中序遍历的结果存储起来,然后再返回需要的结点。
import java.util.ArrayList;
public class Solution {
ArrayList<TreeNode> list=new ArrayList<>();
TreeNode KthNode(TreeNode pRoot, int k)
{
inorder(pRoot);//中序遍历获得一个从小到大有序的序列 并且添加到list里面
if(pRoot==null||k==0||k>list.size())//定义几种为空的情况
return null;
return list.get(k-1);//返回序列中第k个结点(不是值)
}
void inorder(TreeNode root){//二叉搜索树的中序遍历
if(root==null)
return ;
inorder(root.left);
list.add(root);
inorder(root.right);
}
}