码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Kth Smallest Element in a BST

时间:2015-07-03 00:07:34      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

Kth Smallest Element in a BST

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

https://leetcode.com/problems/kth-smallest-element-in-a-bst/

 

 


 

 

这题信息量好大,先是最简单粗暴的解法。

二叉搜索树的特性,先序遍历的输出就是排序的结果。

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @param {number} k
11  * @return {number}
12  */
13 var kthSmallest = function(root, k) {
14     var count = 0;
15     var isFound = false;
16     var res = null;
17     inorder(root);
18     return res;
19 
20     function inorder(node){
21         if(node !== null && !isFound){
22             inorder(node.left);
23             count++;
24             if(count === k){
25                 res = node.val;
26                 isFound = true;
27                 return;
28             }
29             inorder(node.right);
30         }
31     }
32 };

 

 

    [LeetCode][JavaScript]Kth Smallest Element in a BST

    标签:

    原文地址:http://www.cnblogs.com/Liok3187/p/4617323.html

    (0)
    (0)
       
    举报
    评论 一句话评论(0
    登录后才能评论!
    © 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
    迷上了代码!