LeetCode#230 Kth Smallest Element in a BST (week7)
来源:互联网 发布:完成端口开源 编辑:程序博客网 时间:2024/05/22 08:11
week7
题目
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?
原题地址:https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
解析
题目要求找出一颗二叉搜索树中第k小的节点的值。注意到二叉搜索树中对于某个节点,其左子树所有节点的值都小于该节点的值,其右子树所有节点的值都大于该节点的值,因此我们可以采用一个栈来存储遍历过的节点,采用中序遍历的方式从根节点开始遍历,直到栈中的元素个数达到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) { stack<TreeNode*> s; search(root, s, k); return s.top()->val; } void search(TreeNode* t, stack<TreeNode*> &s, int k) { if (!t || s.size() >= k) { return; } if (t->left) { search(t->left, s, k); } if (s.size() < k) { s.push(t); } if (t->right) { search(t->right, s, k); } }};
阅读全文
0 0
- LeetCode#230 Kth Smallest Element in a BST (week7)
- #leetcode#Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- [LeetCode] Kth Smallest Element in a BST
- [LeetCode]Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- [JAVA技术] Java中常用的代码汇总
- 可变长参数列表*args,**kwargs
- 汇编语言-读书知识点记录3
- 洛谷 P1311 选择客栈
- SVN的基本操作
- LeetCode#230 Kth Smallest Element in a BST (week7)
- 【网络编程】Epoll模型讲解
- LINUX-Centos7之后修改默认启动界面为命令界面或者图形界面的方法
- codevs1287方块转换(数学转换)
- [待总结整理]gnuplot笔记
- unity手指触摸事件
- 属性动画+圆环进度条
- React Native 混合编程 之常用API
- 易宝支付相关操作