[C++]Kth Smallest Element in a BST 在一个二叉排序树中找第k小的元素
来源:互联网 发布:浏览器java插件下载 编辑:程序博客网 时间:2024/06/06 16:57
leetcode 原题:https://leetcode.com/problems/kth-smallest-element-in-a-bst/
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.
简要分析:题目的意思很明确,需要我们在二叉排序树中找到第k小元素
因此,根据二叉排序树最大的特点就是左子树的元素小于根节点,右子树的元素大于根节点,中序遍历就可以得到一个从小到大排序的数组。
这样的时间复杂度是O(N)。
但是,如果k = 1呢? 此时你还把所有元素都排序一遍再输出最小的元素是不是就很浪费时间呢?
其实,我们根据中序遍历的特点可以知道,中序遍历输出的元素就是从小到大的,那么如果我们能够记录其遍历输出的元素个数,那么我们就能知道,第k个元素的输出位置。此时就可以终止程序了。
实现代码
#include <iostream>using namespace std;//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;bool flag = false;int times = 0;inorder(root, k, result, flag, times);//root表示节点,k表示需要找到第k小的元素,result保存我们需要的结果,flag判断是否找到了最小元素,times表示当前元素是第times小的元素return result;}void inorder(TreeNode *root, int k, int &result, bool &flag, int ×){if (root == NULL && times >= k)return;if (root->left != NULL){inorder(root->left, k, result, flag, times);} else{flag = true;}if (flag){times++;}if (k == times){result = root->val;return;}if (root->right != NULL){inorder(root->right, k, result, flag, times);}return;}};
0 0
- [C++]Kth Smallest Element in a BST 在一个二叉排序树中找第k小的元素
- Kth Smallest Element in a BST 寻找二叉排序树中第k小元素
- 230. Kth Smallest Element in a BST | 二叉排序树中查找第K小的数
- Kth Smallest Element in a BST 找二叉搜索树中的第k小的元素
- LeetCode OJ 之 Kth Smallest Element in a BST(BST中的第k小元素)
- leetcode_230. Kth Smallest Element in a BST 求二叉搜索树中的第k小的元素,中序遍历法
- LeetCode-230. Kth Smallest Element in a BST (JAVA)二叉树第k小的数字
- LeetCode 230: Kth Smallest Element in a BST 查找二叉排序树
- leetcode230---Kth Smallest Element in a BST(BST中寻找第K小)
- 【二叉树】BST第K小值【230. Kth Smallest Element in a BST】
- [leetcode 230]Kth Smallest Element in a 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
- Jenkins学习总结
- hdu 5424 Rikka with Graph II (哈密顿路判定)
- Linux I2C(一)之常用的几种实例化(i2c_client )
- Mysql的表的碎片清理
- Java关键字final、static使用总结
- [C++]Kth Smallest Element in a BST 在一个二叉排序树中找第k小的元素
- 编写函数,实现许多图片编辑软件都支持的“填充颜色”功能
- 联接与多张表的操作
- Windows mobile 平台 在platform.dat中创建快捷方式,链接到中文路径 字符\Windows\“开始”菜单\设置
- 博客的第一天
- Eigin学习笔记
- 学习路线参考
- CRB and Queries(动态区间求第k小数模板题:线段树套平衡树)
- 自动化测试-TCL脚本语言