Kth Smallest Element in a BST -- leetcode
来源:互联网 发布:linux 编译安装php5.5 编辑:程序博客网 时间:2024/06/05 04:50
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?
基本思路:
进行中序遍历。
/** * 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; while (!s.empty() || root) { while (root) { s.push(root); root = root->left; } root = s.top(); s.pop(); if (!--k) return root->val; root = root->right; } return 0; }};
0 0
- #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
- Leetcode: Kth Smallest Element in a BST
- activity的切换时候无动画的解决办法
- Mybatis使用MySQL进行模糊查询时输入中文检索不到结果
- hdu2010
- 图书管理系统登录菜单的实现
- 程序算法艺术与实践:经典排序算法之插入排序
- Kth Smallest Element in a BST -- leetcode
- session的生命周期
- abstract获取程序运行时间模板
- Oracle临时表 和 插入多条语句 用法
- 【springmvc+mybatis项目实战】杰信商贸-15.细粒度的权限控制+业务上报取消
- 数据库原理
- Android 消息提示框:五种Toast详解
- EL表达式的判断
- java SE复习笔记4