LeetCode:二叉搜索树的第k大节点

LeetCode:二叉搜索树的第k大节点

给定一颗二叉树,返回其第K大节点。
首先的思路就是中序遍历一颗二叉树,得到的结果是有序的,然后从得到的队列中找出第K大的数

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int kthLargest(TreeNode root, int k) {
        int res=0;
        Queue<Integer> queue = new LinkedList<Integer>();
        midSort(root,queue,k);
        int num = queue.size();
        for(int i=0;i<=num-k;i++){
            res = queue.remove();
        }
        return res;
    }
    public void midSort(TreeNode root,Queue<Integer> queue,int k){
         if(root.left!=null){
             midSort(root.left,queue);
         }
         queue.offer(root.val);
         if(root.right!=null){
             midSort(root.right,queue);
         }
        

        
    }
}

但是此方法效率太低,内存消耗太高。
看了其他博主的题解思路,可以进行反向的中序遍历,并观察栈中的元素和K值得比较,满足条件提前结束循环。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int kthLargest(TreeNode root, int k) {
        int res=0;
        // Queue<Integer> queue = new LinkedList<Integer>();
        Stack<Integer> stack = new Stack<Integer>();
        midSort(root,stack,k);
        // int num = queue.size();
        // for(int i=0;i<=num-k;i++){
        //     res = queue.remove();
        // }
        res = stack.pop();
       
        return res;
    }
    public void midSort(TreeNode root,Stack stack,int k){
        
        if(root.right!=null){
            midSort(root.right,stack,k);
        }
        //stack.push(root.val);
        // k--;
        // if(k<0){
        //     return ;
        // }
        if(stack.size()<k)
            stack.push(root.val);
        else{
            return ;
        }
        if(root.left!=null){
            midSort(root.left,stack,k);
        }

        
    }
}

上述代码的执行效率得到了提高。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值