题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思路:如果按照中序遍历一个二叉搜索树,则遍历序列为{2,3,4,5,6,7,8}。
所有先用中序遍历二叉搜索树,就容易找到第k个节点了。
/**
* @author yuan
* @date 2019/2/21
* @description
*/
public class 二叉搜索树的第k个结点 {
static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
private int K = 0;
private TreeNode result = null;
TreeNode KthNode(TreeNode pRoot, int k) {
// 注意使用全局变量保存k
K = k;
if (pRoot != null) {
if (pRoot.left != null) {
KthNode(pRoot.left, K);
}
if (K == 1) {
result = pRoot;
}
--K;
if (pRoot.right != null) {
KthNode(pRoot.right, K);
}
}
return result;
}
}