题解 | #第k轻的牛牛#
第k轻的牛牛
https://www.nowcoder.com/practice/d3b31f055b1640d9b10de0a6f2b8e6f3
题目考察的知识点
考察二叉搜索树的特性
题目解答方法的文字分析
需要先了解:二叉搜索树的中序遍历得到的序列是其节点值递增排序的序列,所以直接中序搜索根节点。这里用了提前终止,只找到第k个即可,不用再往后搜索了。
本题解析所用的编程语言
使用Java解答
完整且正确的编程代码
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param k int整型
* @return int整型
*/
List<Integer> list = new ArrayList<>();
public int kthLighest (TreeNode root, int k) {
// write code here
dfs(root,k);
return list.get(k-1);
}
int count = 0;
public void dfs(TreeNode root, int k){
if(root==null) return;
if(count>k) return; //提前终止 不需要再向后遍历了
count++;
dfs(root.left, k);
list.add(root.val);
dfs(root.right, k);
}
}