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

    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.Show More Hint 

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

    Subscribe to see which companies asked this question

     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     ArrayList<Integer> ans = new ArrayList<Integer>();
    12     public int kthSmallest(TreeNode root, int k) {
    13         InorderTree(root);
    14         return ans.get(k-1);
    15     }
    16     
    17     public void InorderTree(TreeNode node){
    18         if(node != null){
    19             InorderTree(node.left);
    20             ans.add(node.val);
    21             InorderTree(node.right);
    22         }
    23     }
    24 }

    非递归算法使用栈:

     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     public int kthSmallest(TreeNode root, int k) {
    12         Stack<TreeNode> s = new Stack<TreeNode>();
    13         s.push(root);
    14         TreeNode node = root;
    15         while(!s.isEmpty()){
    16             node = s.peek();
    17             if(node.left != null){
    18                 s.push(node.left);
    19                 node.left = null;
    20             }else{
    21                 s.pop();
    22                 k--;
    23                 if(k == 0) return node.val;
    24                 if(node.right != null) s.push(node.right);
    25             }
    26         }
    27         return node.val;
    28     }
    29 }
  • 相关阅读:
    Count on a tree
    图论1 1009
    DP2 1008
    DP1 1008
    NOIP 模拟 1006
    2019 CSP-S 初赛退役记
    9.13——TEST NOIP模拟测试
    [洛谷P2387][NOI2014]魔法森林
    [洛谷P2596][ZJOI2006]书架
    [BZOJ4241]历史研究
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5609651.html
Copyright © 2011-2022 走看看