Algorithm
lc230_二叉搜索树中第K小的元素
进阶思考频繁修改的第k大
思路
暴力: 中序遍历记录到第k个
进阶思考好像是用主席树…但是有点忘了…
看题解原来是bst,记录前后节点数,或者直接进阶到平衡树,可以的
链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/solution/er-cha-sou-suo-shu-zhong-di-kxiao-de-yua-8o07/
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| class MyBst { public: MyBst(TreeNode *root) { this->root = root; countNodeNum(root); }
int kthSmallest(int k) { TreeNode *node = root; while (node != nullptr) { int left = getNodeNum(node->left); if (left < k - 1) { node = node->right; k -= left + 1; } else if (left == k - 1) { break; } else { node = node->left; } } return node->val; }
private: TreeNode *root; unordered_map<TreeNode *, int> nodeNum;
int countNodeNum(TreeNode * node) { if (node == nullptr) { return 0; } nodeNum[node] = 1 + countNodeNum(node->left) + countNodeNum(node->right); return nodeNum[node]; }
int getNodeNum(TreeNode * node) { if (node != nullptr && nodeNum.count(node)) { return nodeNum[node]; }else{ return 0; } } };
class Solution { public: int kthSmallest(TreeNode* root, int k) { MyBst bst(root); return bst.kthSmallest(k); } };
|
Review
boto3 Developer guide
Tips
cosbench配置说明
Cosbench高并发测试失败
Share
samba共享linux目录出来写代码【共享目录有严格格式限制才能成功】