lletcode 230. 二叉搜索树中第K小的元素,链接:https://leetcode.cn/problems/kth-smallest-element-in-a-bst
题目描述
给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。
解法一
直接dfs中序遍历,代码如下:
/*** 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:vector<int> res;int kthSmallest(TreeNode* root, int k) {dfs(root);return res[k - 1];}void dfs(TreeNode* root){if(!root)return;dfs(root->left);res.push_back(root->val);dfs(root->right);}
};
解法二
/*** 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 res = 0;if(root == nullptr || k < 1) {return -1;}int numOfLeftNodes = getNumOfNodes(root->left);int numOfRightNodes = getNumOfNodes(root->right);if (numOfLeftNodes == k - 1) {return root->val;} else if (numOfLeftNodes >= k) {return kthSmallest(root->left, k);} else {return kthSmallest(root->right, k - numOfLeftNodes - 1);}}private:int getNumOfNodes(TreeNode* root) {if (!root) {return 0;}return getNumOfNodes(root->left) + getNumOfNodes(root->right) + 1;}
};