diff --git a/solutions/230. Kth Smallest Element in a BST.md b/solutions/230. Kth Smallest Element in a BST.md new file mode 100644 index 0000000..3dde8ae --- /dev/null +++ b/solutions/230. Kth Smallest Element in a BST.md @@ -0,0 +1,55 @@ +# [30. Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) + +# 思路 +题意要求返回一棵二叉搜索树中第k大的元素。 + +## 思路一 +二叉搜索树有什么特点?二叉搜索树的中序遍历是有序的。因此我们可以用中序遍历解此题,我们需要维护一个count初始为k,每遍历一个节点count就自减1,当count为 +0时当前节点即所求。 + + +## 思路二 +还可以采取分治的思路,即先判断所求节点是在左子树还是右子树。为此我们需要首先得到左子树的节点数left_node_num: +* 若`left_node_num == k - 1`,即当前root即所求; +* 否则,若`left_node_num > k - 1`,即所求节点在左子树,递归进入左子树求解。 +* 否则,即所求节点在左子树,递归进入右子树求解。 + + + +# C++ +## 思路一 +``` C++ +class Solution { +private: + void inorder(TreeNode *root, int &res, int &count){ + if(!root) return; + inorder(root -> left, res, count); + if(!(--count)) res = root -> val; // find it + else inorder(root -> right, res, count); + } +public: + int kthSmallest(TreeNode* root, int k) { + int res = -1; + inorder(root, res, k); + return res; + } +}; +``` + +## 思路二 +``` C++ +class Solution { +private: + int node_num(TreeNode *root){ + if(!root) return 0; + return node_num(root -> left) + node_num(root -> right) + 1; + } +public: + int kthSmallest(TreeNode* root, int k) { + int left_node_num = node_num(root -> left); + if(left_node_num == k - 1) return root -> val; + if(left_node_num > k - 1) return kthSmallest(root -> left, k); + return kthSmallest(root -> right, k - left_node_num - 1); + } +}; +```