[LeetCode from scratch] Kth Smallest Element in a BST
Question:
Given a binary search tree, write a functionkthSmallestTo 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 wocould you optimize the kthSmallest routine?
Answer:
The beauty of programming has a similar question: Find the K large number in an array (unordered. Here is BST, which is already in order, which is more convenient.
If
Left subtreeIf the number is greater than or equal to K, find the K number in the left subtree. If
Left subtreeThe number is equal to the K-1, then the root node is the K; if
Left subtreeIf the number is smaller than K, find the number (K-leftSum-1) in the right subtree (do not forget
Root Node) How many nodes does the left subtree have? Another recursive program is required for calculation.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int findNodeSum(TreeNode* root) { if (root == NULL) return 0; return (findNodeSum(root->left) + findNodeSum(root->right) + 1); } int kthSmallest(TreeNode* root, int k) { int leftSum = findNodeSum(root->left); if (leftSum >= k) return kthSmallest(root->left, k); else if (leftSum == k - 1) return root->val; else { return kthSmallest(root->right,k - leftSum - 1); } }};The question is not complete yet. What if BST is always modifying?
It is best to modify the tree node Structure and add an attribute: Total number of nodes in the left subtree. In this way, the search complexity is O (height)