Topic
Given a binary search tree, write a function kthsmallest to find the k smallest element.
Description
You can assume that K is always valid, 1≤k≤ two forks to search for the number of tree elements.
Example 1:
Input:root = [3,1,4,null,2], k = 1
3 / 1 4 2
Output:1
Example 2:
Input:root = [5,3,6,2,4,null,null,1], k = 3
5 / 3 6 / 2 4 / 1
Output:3
Advanced:
If the binary search tree is often modified (insert/delete operations) and you need to find k
the small value frequently, how would you optimize the kthSmallest
function?
Exercises
Writing leetcode for the first time is not very good.
In the public
definition of a function recursive sequence traversal, record the answer, found when return
it can.
Do not spit slot variable name
/** * 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 index = 0, final_attack_ride; void Solve(TreeNode* root, const int &k) { if (root->left) { Solve(root->left, k); } if (index >= k) return; if (++index == k) { final_attack_ride = root->val; return; } if (root->right) { Solve(root->right, k); } } int kthSmallest(TreeNode* root, int k) { Solve(root, k); return final_attack_ride; }};
Leetcode 230. Binary search tree small element K (balance tree)