zoukankan      html  css  js  c++  java
  • LeetCode OJ 230. Kth Smallest Element in a BST

    Total Accepted: 46445 Total Submissions: 122594 Difficulty: Medium

    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?

    Hint:

    1. Try to utilize the property of a BST.
    2. What if you could modify the BST node's structure?
    3. The optimal runtime complexity is O(height of BST).

    Credits:
    Special thanks to @ts for adding this problem and creating all test cases.

    二叉搜索树特点是对于任意一个节点,它的左子树的节点值都比它小,它的右子树的值都比它大。因此可以从树的最左边向上递归,同时计数,直到计数达到当前指定数字。
     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     private int cnt = 0;
    12     public int kthSmallest(TreeNode root, int k) {
    13         int result = 0;
    14         if(root != null){
    15             result = kthSmallest(root.left,k);
    16             cnt++;
    17             if(cnt == k){
    18                 return root.val;
    19             }
    20             result += kthSmallest(root.right,k);
    21         }
    22         return result;
    23     }
    24 }
  • 相关阅读:
    CF 142B Tprimes
    CF 231A Team
    poj 2001 Shortest Prefixes ——字典树入门
    hdu 1039 Easier Done Than Said?
    poj 2528 Mayor's posters
    hdu 1061 Rightmost Digit
    poj 2503 Babelfish
    CF271 A. Beautiful Year
    poj 2752
    CF271 B. Prime Matrix
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5475286.html
Copyright © 2011-2022 走看看