LeetCode:44.二叉搜索树中第K小的元素
目录
1.二叉搜索树中第K小的元素
1.二叉搜索树中第K小的元素
这道题可以先进行中序遍历,因为二叉搜索树的中序遍历是有序的,所以每当遍历一个节点的时候,k--,当k减到0的时候,对应的值就是第K小的元素
class Solution {int ret;int count;
public:int kthSmallest(TreeNode* root, int k) {count = k;dfs(root);return ret;}void dfs(TreeNode* root){if(root == 0 || count == 0)return;dfs(root->left);count--;if(count == 0) ret = root->val;dfs(root->right);}
};