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 }
  • 相关阅读:
    (转)Hibernate 注解详解
    PHP - jsPDF+html2canvas实现网页截图导出PDF
    (转)PHP-Sublime Text3插件&快捷键(MAC)
    POI
    maven中使用jstl
    树莓派使用pptpd搭建PPTP服务器
    树莓派网络对时
    Debian 安装 oracle java
    让树莓派(RaspberryPi)显示中文
    树莓派搭建minecraft服务器
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5475286.html
Copyright © 2011-2022 走看看