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 }
  • 相关阅读:
    [Noip2017]逛公园
    [NOI2005]瑰丽华尔兹
    codeforces 558E A Simple Task
    bzoj1812 riv(树形背包)
    bzoj 1009 GT考试
    bzoj1030 文本生成器 Trie图+dp
    bzoj1500 维修数列(splay)
    [NOI2008]假面舞会
    测试用例的基本知识
    使用Xmind编写测试用例
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5609651.html
Copyright © 2011-2022 走看看