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 }
  • 相关阅读:
    天啦噜!原来Chrome自带的开发者工具能这么用你知道么!
    JavaScript易错知识点整理
    2016年开源巨献:来自百度的71款开源项目
    前端js面试中的常见的算法问题
    详解JS跨域问题
    console 输出信息
    js身份证校验
    阻止页面回退
    pc端js常用方法
    js实现QQ、微信、新浪微博分享功能
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5609651.html
Copyright © 2011-2022 走看看