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 }
  • 相关阅读:
    Element UI表格组件技巧:如何简洁实现跨页勾选、跨页统计功能
    Spring Cloud Gateway转发Spring WebSocket
    mac OS 安装配置Nginx服务器
    异常处理
    模块和包调用方法、执行顺序
    模块:序列化
    模块:random
    模块:time
    模块:collections,Python中的扩展数据类型
    re模块的基本用法
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5609651.html
Copyright © 2011-2022 走看看