zoukankan      html  css  js  c++  java
  • [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;
        }
    }
  • 相关阅读:
    数据库范式那些事[转]
    C# 之值类型与引用类型参数[基础]
    C# 实体类生成工具
    《浅谈线程池》笔记
    提高网站性能之 —— 减少图片HTTP 请求的方案
    SQL Server 2005 For XML[学习]
    关于数据类型导致的精确计算
    SQL Server 数据库实现之TSQL语句[备忘]
    C# 关键字ref 和out 的详细区别
    关于XML中的名称空间
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4713363.html
Copyright © 2011-2022 走看看