zoukankan      html  css  js  c++  java
  • leetcode 230: Kth Smallest Element in a BST

    Kth Smallest Element in a BST

    Total Accepted: 3655 Total Submissions: 12149

    Given a binary search tree, write a function kthSmallest to find thekth 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?

    [思路]

    能够用递归和非递归. 这里我用了非递归的方法, 类似于 binary tree iterator. 顺便提一下, 我看了下网上的递归方法,时间复杂度非常高,每次都要算tree size. 感觉即使是递归,也应该还能optimize.

    Follow up 挺有意思, 须要在节点中保留一些额外的信息: 左子树的大小. 在插入删除时也要同一时候维护左子树的大小. 再查找时,能够用二分. 时间复杂度为O(h)

    [CODE]

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int kthSmallest(TreeNode root, int k) {
            Stack<TreeNode> stack = new Stack<>();
            TreeNode n = root;
            while(n.left!=null) {
                stack.push(n);
                n = n.left; 
            }
            
            while(k>0 && (n!=null || !stack.isEmpty())) {
                if(n==null) {
                    n = stack.pop();
                    if(--k==0) return n.val;
                    n = n.right;
                } else {
                    stack.push(n);
                    n = n.left;
                }
            }
            return n.val;
        }
    }


  • 相关阅读:
    一、CentOS 7安装部署GitLab服务器

    四、指定Nginx启动用户
    三、Nginx支持php
    二、Nginx多站点配置(参考宝塔的)分析
    一、Nginx多站点配置
    一、PHP和Apache实现多用户自助建站
    Flask+uwsgi+Nginx+Ubuntu部署
    flask 上传头像
    flask 分页
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/6783102.html
Copyright © 2011-2022 走看看