【LeetCode】面试题54. 二叉搜索树的第k大节点

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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值