目录
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/
题目描述:
给定一棵二叉搜索树,请找出其中第k大的节点。
示例 1:
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 4
1. 自己的第一代解法(很差劲儿):(13 ms)(41.1 MB)
层序遍历,将结点数值存在list中,将list转化成数组,sort排序一下,返回倒数第k个
public int kthLargest(TreeNode root, int k) {
Queue<TreeNode> queue = new LinkedList<>();
List<Integer> list = new LinkedList<>();
queue.add(root);
TreeNode tmp;
while (!queue.isEmpty()) {
tmp = queue.remove();
if (tmp.left != null)
queue.add(tmp.left);
if (tmp.right != null)
queue.add(tmp.right);
list.add(tmp.val);
}
Integer[] arr = new Integer[list.size()];
arr = list.toArray(arr);
Arrays.sort(arr);
return arr[arr.length - k];
}
2. 网友好的解法(对二叉搜索树的理解很深):(1 ms)(41 MB)
思路:
用一个栈来实现一个排列树的从大到小弹出。
过程图如下图:
代码如下:
class Solution {
public int kthLargest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
TreeNode tmp = root;
int count = k;
TreeNode pop;
while (true) {
while (tmp != null) {
stack.push(tmp);
tmp = tmp.right;
}
pop = stack.pop();
count--;
if (count == 0) {
return pop.val;
}
tmp = pop.left;
}
}
}
3. 自己最后琢磨出的算法:(0 ms)(40.7 MB)
此解法运用了,二叉搜索树的从大到小遍历。运用了递归的算法
当遍历到第k大节点的时候,将数值赋值给res成员变量
返回成员变量res的值即可
class Solution {
private int count;
private int res;
//找到二叉搜索树的第k大节点值
//二叉搜索树的自创式排序,先右,再中间,再左边,这样就是从大到小排序
public int kthLargest(TreeNode root, int k) {
count = k;
method(root);
return res;
}
public void method(TreeNode root){
if(count == 0 || root == null){
return;
}
method(root.right);
count --;
if(count == 0){
res = root.val;
}
method(root.left);
}
}