230. Kth Smallest Element in a BST
来源:互联网 发布:淘宝规则在哪里查看 编辑:程序博客网 时间:2024/05/16 11:50
Given a binary search tree, write a function kthSmallest
to 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:
在每个二叉树节点中添加一个记录以当前节点为根的子树中节点的个数,进行插入删除操作时,需要在插入点和删除点至根节点的路径上的所有节点的计数域进行维护,
然后查找的时候由于二叉查找树的性质,根据这个计数域进行查找即可。
0 0
- 230.Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 最保险的函数间数组作为参数值传递与返回方法,用memcpy函数!
- ZooKeeper分布式过程协同技术详解
- Oracle查询死锁及处理方法
- C++ Primer 学习笔记_96_用以大型程序的工具 -多重继承与虚继承[续1]
- C++ Primer 学习笔记_97_用来大型程序的工具 -多重继承与虚继承[续2]
- 230. Kth Smallest Element in a BST
- Android应用发送短信的实现
- 八大排序算法 之 归并排序
- 如果让我设计拉勾移动端 App
- codeforces 670B Game of Robots
- js--函数--3.函数属性和方法
- hadoop的回收站功能
- c++中的const总结
- Leetcode哈希表类题目