標籤:
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:
- 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/
這題資訊量好大,先是最簡單粗暴的解法。
二叉搜尋樹的特性,先序遍曆的輸出就是排序的結果。
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} root10 * @param {number} k11 * @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