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:
- Try to utilize the property of a BST.
- What if you could modify the BST node ' s structure?
- 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