国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 斗六市| 磐安县| 阳新县| 萝北县| 尚志市| 渝中区| 横峰县| 静安区| 济南市| 石泉县| 连城县| 鹿邑县| 安吉县| 巴塘县| 邵东县| 永登县| 南雄市| 阜阳市| 拉萨市| 米林县| 合肥市| 凤山县| 水城县| 枞阳县| 恩平市| 师宗县| 临清市| 崇州市| 巴马| 普安县| 金坛市| 周宁县| 临泽县| 城步| 和田市| 浪卡子县| 古田县| 循化| 平乐县| 根河市| 宿迁市|