• [leedcode 230] Kth Smallest Element in a BST


    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?

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
      /*  两种思路: 
            1.空间换时间 
            BST的特性是,如果按照中序排列,得到的递增序;所以可以使用一个stack进行中序遍历,直到找到第K个元素; 
            2. 树树的结点数 
            对于每个节点root,计算以它为根节点的左子树的节点数,计作S。 
            如果S+1==K,返回root->val; 
            如果S+1 > K,在root的左子树里面查找第K小元素; 
            如果S+1 > k ,在root的右子树里面查找第k-s-1小元素*/
        public int kthSmallest(TreeNode root, int k) {
            /*Stack<TreeNode> stack=new Stack<TreeNode>();
            while(!stack.isEmpty()||root!=null){
                while(root!=null){
                    stack.push(root);
                    root=root.left;
                }
                TreeNode temp=stack.pop();
                k--;
                if(k==0){
                    return temp.val;
                }
                root=temp.right;
            }
            return 0;*/
            if(root==null) return 0;
            int left=find(root.left);
            if(left+1==k) return root.val;
            if(left+1<k) return kthSmallest(root.right,k-left-1);
            else return kthSmallest(root.left,k);
    
        }
        public int find(TreeNode p){
            if(p==null) return 0;
            return find(p.left)+find(p.right)+1;
        }
    }
  • 相关阅读:
    d3js 获取元素以及设置属性
    javascript 转义函数
    es6 对象浅拷贝的2种方法
    SwitchyOmega 代理设置
    table 设置边框
    Highcharts 配置选项详细说明
    windows环境下生成ssh keys
    vue 给组件绑定原生事件
    Vue 字面量语法 vs 动态语法
    Vue 2.0 v-for 响应式key, index及item.id参数对v-bind:key值造成差异研究
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4713363.html
Copyright © 2020-2023  润新知