Given the root
of a binary search tree, and an integer k
, return the kth
smallest value (1-indexed) of all the values of the nodes in the tree.
Example 1:
Input: root = [3,1,4,null,2], k = 1 Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3 Output: 3
Constraints:
n
.1 <= k <= n <= 104
0 <= Node.val <= 104
题目:给定一个二叉查找树,返回第K小的值
思路:树的inorder遍历的变体。
方法一:迭代法,代码:
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- int kthSmallest(TreeNode* root, int k) {
- int count = 0;
- stack
stk; - TreeNode* node = root;
- while(!stk.empty() || node){
- while(node){
- stk.push(node);
- node = node->left;
- }
- node = stk.top();
- stk.pop();
- count++;
- if(count == k) return node->val;
- node = node->right;
- }
- return -1;
- }
- };
方法二,递归法,代码:
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- bool DFS(TreeNode* node, int k, int& pos, int& res){
- if(!node || pos > k) return false;
- bool left = DFS(node->left, k, pos, res);
- if(left) return true;
- pos++;
- if(pos == k){
- res = node->val;
- return true;
- }
- return DFS(node->right, k, pos, res);
-
- }
- int kthSmallest(TreeNode* root, int k) {
- int pos = 0, res = 0;
- DFS(root, k, pos, res);
- return res;
- }
- };