题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
练习地址
实现
方法:中序遍历数值递增
// 中序输出递增
public class C54_tree_GetKth {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
static int k = 0;
static TreeNode kthNode(TreeNode root, int n) {
if (root == null || n == 0) {
return null;
}
k = n;
return kthNodeCore(root);
}
static TreeNode kthNodeCore(TreeNode root) {
TreeNode res = null;
if (root.left != null) {
res = kthNodeCore(root.left);
}
if (res == null) {
if (k == 1) {
res = root;
}
k--;
}
if (res == null && root.right != null) {
res = kthNodeCore(root.right);
}
return res;
}
}
Test
public static void main(String[] args) {
TreeNode root = new TreeNode(5);
TreeNode node3 = new TreeNode(3);
TreeNode node2 = new TreeNode(2);
TreeNode node4 = new TreeNode(4);
TreeNode node6 = new TreeNode(6);
TreeNode node7 = new TreeNode(7);
TreeNode node8 = new TreeNode(8);
root.left = node3;
root.right = node7;
node3.left = node2;
node3.right = node4;
node7.left = node6;
node7.right = node8;
System.out.println(kthNode(root, 1).val);
System.out.println(kthNode(root, 2).val);
System.out.println(kthNode(root, 3).val);
System.out.println(kthNode(root, 4).val);
System.out.println(kthNode(root, 5).val);
System.out.println(kthNode(root, 6).val);
System.out.println(kthNode(root, 7).val);
//2,3,4,5,6,7,8
}