博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
平衡二叉树中第k小的数 Kth Smallest Element in a BST
阅读量:6715 次
发布时间:2019-06-25

本文共 1471 字,大约阅读时间需要 4 分钟。

  hot3.png

问题:

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 

You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Follow up:

What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

解决:

① 借助中序遍历。

class Solution {//3ms

    public int kthSmallest(TreeNode root, int k) {
        List<Integer> list = new ArrayList<>();
        inorder(root,list);
        int res = list.get(k - 1);
        return res;
    }
    public void inorder(TreeNode root,List<Integer> list){
        if (root == null) return;
        inorder(root.left,list);
        list.add(root.val);
        inorder(root.right,list);
    }
}

② 借助栈实现中序遍历。

class Solution {//2ms

    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null){
            stack.push(cur);
            cur = cur.left;
        }
        int count = 0;
        while (! stack.isEmpty()){
            cur = stack.pop();
            count ++;
            if (count == k){
                return cur.val;
            }
            TreeNode tmp = cur.right;
            while (tmp != null){
                stack.push(tmp);
                tmp = tmp.left;
            }
        }
        return -1;
    }
}

③ 在中序遍历过程中查找第k小的值。

class Solution { //0ms

    int count = 0;
    int res = 0;
    public int kthSmallest(TreeNode root, int k) {
        count = k - 1;
        inorder(root);
        return res;
    }
    public void inorder(TreeNode root){
        if (root == null || count < 0){
            return;
        }
        inorder(root.left);
        if (count == 0){
            res = root.val;
            count --;
        }
        count --;
        inorder(root.right);
        
    }
}

转载于:https://my.oschina.net/liyurong/blog/1591587

你可能感兴趣的文章
svn (subversion)+Apache(httpd)+SSL(openssl)的配置
查看>>
Web Farm与网络负载平衡概述及架构示例
查看>>
管理Exchange Server 2007传输拓扑
查看>>
Android绘制进阶之二:文本的绘制
查看>>
CentOS5.6下安装安装配置vsftp
查看>>
ECLIPSE里面SVN图标消失,文件状态不显示问题
查看>>
NMAP网络扫描嗅探工具。
查看>>
java-第九章-循环结构进阶-输入行数,打印直角三角行
查看>>
Android中检查网络连接状态的变化,无网络时跳转到设置界面
查看>>
Design Pattern学习笔记 --- Builder(生成器)模式
查看>>
找出日志中的错误信息并发送邮件
查看>>
6. SQL Server数据库监控 - 如何告警
查看>>
消失了的自己
查看>>
python监测硬盘使用率、获取内存使用率
查看>>
我的友情链接
查看>>
java学习之路
查看>>
centos6.5 x64桌面版装virtualbox5.1
查看>>
医疗信息化、医学、医院管理资料下载
查看>>
RAID 10和raid 01
查看>>
设计模式---代理模式
查看>>