Question

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).

Solution 1 -- Inorder Traversal

Again, we use the feature of inorder traversal of BST. But this solution is not best for follow up. Time complexity O(n), n is the number of nodes.

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int kthSmallest(TreeNode root, int k) {
TreeNode current = root;
Stack<TreeNode> stack = new Stack<TreeNode>();
while (current != null || !stack.empty()) {
if (current != null) {
stack.push(current);
current = current.left;
} else {
TreeNode tmp = stack.pop();
k--;
if (k == 0) {
return tmp.val;
}
current = tmp.right;
}
}
return -1;
}
}

Solution 2 -- Augmented Tree

The idea is to maintain rank of each node. We can keep track of elements in a subtree of any node while building the tree. Since we need K-th smallest element, we can maintain number of elements of left subtree in every node.

Assume that the root is having N nodes in its left subtree. If K = N + 1, root is K-th node. If K < N, we will continue our search (recursion) for the Kth smallest element in the left subtree of root. If K > N + 1, we continue our search in the right subtree for the (K – N – 1)-th smallest element. Note that we need the count of elements in left subtree only.

Time complexity: O(h) where h is height of tree.

(referrence: GeeksforGeeks)

Here, we construct tree in a way that is taught during Algorithm class.

"size" is an attribute which indicates number of nodes in sub-tree rooted in that node.

Time complexity: constructing tree O(n), find Kth smallest number O(h).

start:
if K = root.leftElement + 1
root node is the K th node.
goto stop
else if K > root.leftElements
K = K - (root.leftElements + 1)
root = root.right
goto start
else
root = root.left
goto srart stop
 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class ImprovedTreeNode {
int val;
int size; // number of nodes in the subtree that rooted in this node
ImprovedTreeNode left;
ImprovedTreeNode right;
public ImprovedTreeNode(int value) {val = value;}
} public class Solution { // Construct ImprovedTree recursively
public ImprovedTreeNode createAugmentedBST(TreeNode root) {
if (root == null)
return null;
ImprovedTreeNode newHead = new ImprovedTreeNode(root.val);
ImprovedTreeNode left = createAugmentedBST(root.left);
ImprovedTreeNode right = createAugmentedBST(root.right);
newHead.size = 1;
if (left != null)
newHead.size += left.size;
if (right != null)
newHead.size += right.size;
newHead.left = left;
newHead.right = right;
return newHead;
} public int findKthSmallest(ImprovedTreeNode root, int k) {
if (root == null)
return -1;
ImprovedTreeNode tmp = root;
int leftSize = 0;
if (tmp.left != null)
leftSize = tmp.left.size;
if (leftSize + 1 == k)
return root.val;
else if (leftSize + 1 > k)
return findKthSmallest(root.left, k);
else
return findKthSmallest(root.right, k - leftSize - 1);
} public int kthSmallest(TreeNode root, int k) {
if (root == null)
return -1;
ImprovedTreeNode newRoot = createAugmentedBST(root);
return findKthSmallest(newRoot, k);
}
}

Kth Smallest Element in a BST 解答的更多相关文章

  1. 【LeetCode】230. Kth Smallest Element in a BST (2 solutions)

    Kth Smallest Element in a BST Given a binary search tree, write a function kthSmallest to find the k ...

  2. [leetcode] 230. Kth Smallest Element in a BST 找出二叉搜索树中的第k小的元素

    题目大意 https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/ 230. Kth Smallest Elem ...

  3. LeetCode 230. 二叉搜索树中第K小的元素(Kth Smallest Element in a BST)

    230. 二叉搜索树中第K小的元素 230. Kth Smallest Element in a BST 题目描述 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的 ...

  4. 【刷题-LeetCode】230. Kth Smallest Element in a BST

    Kth Smallest Element in a BST Given a binary search tree, write a function kthSmallest to find the k ...

  5. leetCode(46):Kth Smallest Element in a BST

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

  6. [LeetCode] Kth Smallest Element in a BST 二叉搜索树中的第K小的元素

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

  7. Leetcode Kth Smallest Element in a BST

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

  8. Leetcode 230. Kth Smallest Element in a BST

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

  9. Kth Smallest Element in a BST

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

随机推荐

  1. HashMap和Hashtable的差别

     1. HashMap 与 Hashtable继承自不同的类 1) HashMap 继承自AbstractMap,而AbstractMap实现了Map接口 2) Hashtable 继承自Dict ...

  2. windows phone之获取当前连接WIFI的SSID

    public string GetSSIDName() { foreach (var network in new NetworkInterfaceList()) { if ( (network.In ...

  3. WifiDog系统

    WifiDog:A captive portal suite What is it composed of ? A: It is composed of 2 components: The clien ...

  4. <转载>僵尸进程

    转载http://www.cnblogs.com/scrat/archive/2012/06/25/2560904.html 什么是僵尸进程 僵尸进程是指它的父进程已经退出(父进程没有等待(调用wai ...

  5. (转)linux下fork的运行机制

    转载http://www.cnblogs.com/leoo2sk/archive/2009/12/11/talk-about-fork-in-linux.html 给出如下C程序,在linux下使用g ...

  6. android滑动基础篇 - 触屏显示信息

    效果图: 代码部分: activity类代码: package com.TouchView; /* * android滑动基础篇 * */ import android.app.Activity; i ...

  7. JavaScript面向对象之类的创建

    JavaScript对象的定义: 在js中函数极为对象,对象分为二种:对象字变量产生的对象连接到Object.prototype:函数对象连接到Function.prototype 方法:当一个函数被 ...

  8. 【转】Android中自动连接到指定SSID的Wi-Fi

    最近在做一个项目,其中涉及到一块“自动连接已存在的wifi热点”的功能,在网上查阅了大量资料,五花八门,但其中一些说的很简单,即不能实现傻瓜式的拿来就用,有些说的很详细,但其中不乏些许错误造成功能无法 ...

  9. 【转】NAT路由器打洞原理

    什么是打洞,为什么要打洞 由于Internet的快速发展 IPV4地址不够用,不能每个主机分到一个公网IP 所以使用NAT地址转换. 下面是我在网上找到的一副图 一般来说都是由私网内主机(例如上图中“ ...

  10. 如何在已经存在python2的linux环境上安装python3

    最近看到好多人都在问在已经存在python2.7的环境下如何安装python3,于是我决定写下这篇文档,供大家学习参考,希望能够给大家带来帮助 有的人在安装的时候可能会先将python2卸载掉,这个地 ...