leetcode230:Kth Smallest Element in a BST
来源:互联网 发布:时间序列数据集下载 编辑:程序博客网 时间:2024/06/05 19:18
Description:
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?
思路:
二叉搜索树是一种特殊的二叉树,具有以下性质:
**1. 如果左子树不为空,左子树上结点的值均小于根节点的值
2. 如果右子树不为空,右子树结点上的值均大于根节点的值
3. 左右子树也分别为二叉搜索树**
通过性质我们得知,左子树<根节点<右子树。我们学过三种树的遍历,中序遍历,则刚好是从左子树到根节点到右子树遍历,即可得到一个递增的序列,然后找到第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 kthSmallest(TreeNode *root,int k) { int result = 0; int index = 0; if(k < 1) return -1; InOrder(root, k, index, result); return result; } void InOrder(TreeNode *root, int k, int &index, int &result) { if (root) { InOrder(root->left, k, index, result); index++;//计数 if (index == k) { result = root->val; } InOrder(root->right, k, index, result); } }};
非递归方法:
class Solution { //非递归方法:public: int kthSmallest(TreeNode *root, int k) { int index = 0; TreeNode *cur = root; stack<TreeNode*> s; while (cur || !s.empty()){ while (cur){ s.push(cur); cur = cur->left; } cur = s.top(); //返回栈顶元素 s.pop(); index++; if (index == k) return cur->val; cur = cur->right; } return 0; }};
阅读全文
0 0
- LeetCode230:Kth Smallest Element in a BST
- Leetcode230 Kth Smallest Element in a BST
- LeetCode230 Kth Smallest Element in a BST
- LeetCode230. Kth Smallest Element in a BST
- leetcode230:Kth Smallest Element in a BST
- LeetCode230——Kth Smallest Element in a BST
- leetcode230:Kth Smallest Element in a BST(medium)
- leetcode230---Kth Smallest Element in a BST(BST中寻找第K小)
- #leetcode#Kth Smallest Element in a BST
- 230.Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- 《Python数据分析常用手册》一、NumPy和Pandas篇
- PHP类的自动加载
- Bootstrap——按钮,按钮组,图片,文字,背景,下拉菜单
- Authorizer、PermissionResolver及RolePermissionResolver
- Java的注解机制——Spring自动装配的实现原理
- leetcode230:Kth Smallest Element in a BST
- Markdown特殊字符显示
- Linux系统下的20个常用命令(初)
- 强化学习资料
- spring 数据库事务管理
- 在ElasticSearch之下(图解搜索的故事)
- 高并发系统设计之开放平台API接口调用频率控制系统
- Bootstrap——输入框组
- Http请求中Content-Type讲解以及在Spring MVC中的应用