[Leetcode 230, Medium] Kth Smallest Element in a BST
2015-07-18 00:26
435 查看
Problem:
Given a binary search tree, write a function
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?
Hint:
Try to utilize the property of a BST.
Analysis:
Solutions:
C++:
Python:
Given a binary search tree, write a function
kthSmallestto 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?
Hint:
Try to utilize the property of a BST.
Analysis:
Solutions:
C++:
int kthSmallest(TreeNode* root, int k) { stack<TreeNode *> node_stack; node_stack.push(root); TreeNode *p_cur_node = root->left; while(p_cur_node || !node_stack.empty()) { if(p_cur_node) { node_stack.push(p_cur_node); p_cur_node = p_cur_node->left; continue; } if(!node_stack.empty()) { p_cur_node = node_stack.top(); --k; if(k == 0) return p_cur_node->val; node_stack.pop(); p_cur_node = p_cur_node->right; } } return -1; }Java:
Python:
相关文章推荐
- Socket API回顾
- SDK & MFC
- Android--IntentService简介
- 设计模式--享元模式
- Comet技术在IM上的应用
- 二分图匹配之匈牙利算法
- mysql之触发器
- uva 10054 欧拉回路
- 摘自大牛的见解
- MySQL导入和导出数据库的方法
- 立德、立言、立行
- 1044: [HAOI2008]木棍分割
- 博文点评后的一点闲扯
- linux_oracle配置文档
- Lowest Common Ancestor of a Binary Tree
- linux_DHCP配置文档
- openerp学习笔记 模块结构分析
- 函数的定义和调用
- 黑马程序员----java网络编程基础
- pat 1027. Colors in Mars (20)