题目描述
给定一棵二叉搜索树,请找出其中的第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;
}
}
*/
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
Queue<TreeNode> q=new LinkedList<TreeNode>();
TreeNode KthNode(TreeNode pRoot, int k){
putNodeintoStack(pRoot);//根据根元素对二叉树进行中序遍历
TreeNode curnode = null;
int len=q.size();
if(len<k) return null;
for(int i=0;i<k;i++)//从0开始,获取队列的第k-1个元素
curnode =q.poll();
return curnode;
}
void putNodeintoStack(TreeNode pRoot){
//二叉搜索树即是二叉排序树,对二叉树进行中序遍历,就能获得有序序列
if(pRoot==null)
return ;
if(pRoot.left!=null)
putNodeintoStack(pRoot.left);
q.offer(pRoot);
if(pRoot.right!=null)
putNodeintoStack(pRoot.right);
}
}