问题:
难度:easy
说明:
给定一个二叉查询树,找到第K个最小的数。很简单的一道题,主要考数据结构,找第几个最小数,说实在二叉查询数都已经排好序了,来个前序遍历就行了,当然得要记得数据结构就是。
输入案例:
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
输入范围:
1、K一定在树节点数量范围内,不会说K超过树节点数。
2、二叉树节点不会少于1,不会大于10^4。
我的代码:
挺简单的,记住了什么是前序遍历和二叉查询树就好办。
class Solution {
// 将K存到属性中
int k;
// 计算二叉树遍历索引
int index;
// 记录目标数据
int target;
public int kthSmallest(TreeNode root, int k) {
this.k = k;
recurtion(root);
return target;
}
public void recurtion(TreeNode root) {
// index == k表明已经找到了
if(index < k) {
// 先遍历左节点
if(root.left != null) {
recurtion(root.left);
}
// 左边完了判断一次是否第k个
index ++;
if(index == k) target = root.val;
// 再遍历右键点
if(root.right != null) {
recurtion(root.right);
}
}
}
}