230. Kth Smallest Element in a BST
2016-05-07 10:19
423 查看
Given a binary search tree, write a function
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?
水一发啊,水一发~~~
Follow Up:
在每个二叉树节点中添加一个记录以当前节点为根的子树中节点的个数,进行插入删除操作时,需要在插入点和删除点至根节点的路径上的所有节点的计数域进行维护,
然后查找的时候由于二叉查找树的性质,根据这个计数域进行查找即可。
kthSmallestto find thekth 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?
水一发啊,水一发~~~
/** * 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: void dfs(TreeNode *root, int &ret, int &k) { if(k == 0) return ; if(root->left != NULL) { dfs(root->left, ret, k); } if(--k == 0) { ret = root->val; return ; } if(root->right != NULL) { dfs(root->right, ret, k); } return ; } int kthSmallest(TreeNode* root, int k) { if(root == NULL) return 0; int ans; dfs(root, ans, k); return ans; } };
Follow Up:
在每个二叉树节点中添加一个记录以当前节点为根的子树中节点的个数,进行插入删除操作时,需要在插入点和删除点至根节点的路径上的所有节点的计数域进行维护,
然后查找的时候由于二叉查找树的性质,根据这个计数域进行查找即可。
相关文章推荐
- Java IO流中的flush()
- TCP协议选项
- nyoj 323 BUYING FEED 贪心
- com.genuitec.runtime.generic.jee60 is not defined
- 4+1视图与UML对应关系
- Contiki 配置参数“技巧”说明
- Leetcode哈希表类题目
- 如果让我设计拉勾移动端 App
- c++中的const总结
- GoF23种设计模式之行为型模式之模板方法
- 字符串处理函数(续)
- 189. Rotate Array
- 关于UIScrollView的约束问题
- 链表系列之单链表——使用单链表实现大整数相加
- js--函数--3.函数属性和方法
- hadoop的回收站功能
- codeforces 670B Game of Robots
- 最保险的函数间数组作为参数值传递与返回方法,用memcpy函数!
- Android应用发送短信的实现
- hadoop集群环境搭建准备工作