国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

230. Kth Smallest Element in a BST

2019-11-08 02:05:43
字體:
供稿:網(wǎng)友

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.

Follow up: What if the BST is modified (insert/delete Operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

思路:就是利用中序遍歷的結(jié)果是遞增的,然后找到第k小

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int rank = 0, num; bool r = true; void inorder(TreeNode* root, int k){ if(r){ if(root == NULL) return ; inorder(root->left, k); ++rank; if(rank == k) { num = root->val; r = false; return; } inorder(root->right, k); } } int kthSmallest(TreeNode* root, int k) { inorder(root, k); return num; }};
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 明星| 德兴市| 宁远县| 淮安市| 卢氏县| 双桥区| 黑河市| 米林县| 铜陵市| 兰州市| 星子县| 中牟县| 镇平县| 大同县| 太保市| 延川县| 东莞市| 都昌县| 宣汉县| 仪征市| 邯郸市| 会理县| 张家口市| 铜川市| 漠河县| 监利县| 额尔古纳市| 长岭县| 南充市| 普兰县| 岳池县| 通河县| 宁安市| 会宁县| 静安区| 梅州市| 轮台县| 东乌| 西青区| 宿州市| 成安县|