[Leetcode] [JavaScript] Kth smallest Element in a BST

Source: Internet
Author: User

Kth smallest Element in a BST

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

Note:
You may assume k are always valid, 1≤k≤bst's total elements.

Follow up:

What if the BST are modified (Insert/delete operations) often and you need to find the kth smallest frequently? How would 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/

The information is very large, first of all the most simple and rough solution.

The characteristics of binary search tree, the output of first order traversal is the result of sorting.

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} rootTen * @param {number} K One * @return {number} A  */ - varKthsmallest =function(root, k) { -     varCount = 0; the     varIsfound =false; -     varres =NULL; - inorder (root); -     returnRes; +  -     functioninorder (node) { +         if(Node!==NULL&&!isfound) { A inorder (node.left); atcount++; -             if(Count = =k) { -res =Node.val; -Isfound =true; -                 return; -             } in inorder (node.right); -         } to     } +};

    [leetcode][javascript]kth smallest Element in a BST

    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.