leetcode-230. Kth Smallest Element in a BST
来源:互联网 发布:js获取当前时间加一年 编辑:程序博客网 时间:2024/05/17 03:09
链接: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.
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?
题目的意思:给一个二叉搜索树,然后我们在二叉搜索树当中去查找第k小的树。
直接说思路了:比较简单,中序遍历一次找到第k小的就行了。
AC代码如下
public class Solution { int n=0; int k=0; public int kthSmallest(TreeNode root, int k) { this.k=k; return mid(root); } public int mid(TreeNode node){ if(node==null){ return Integer.MIN_VALUE; } int res=mid(node.left); if(res!=Integer.MIN_VALUE){ return res; } n++; if(n==k){ return node.val; } res=mid(node.right); if(res!=Integer.MIN_VALUE){ return res; } return Integer.MIN_VALUE; }}
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
- xlistview上拉刷新、下拉加载
- hdu 5686 Problem B【水题】
- OKHttp通信使用(二)
- 定制bootstrap模态框的header
- windows7下安装ruby,rubyGems和devkit
- leetcode-230. Kth Smallest Element in a BST
- js页面跳转整理
- viewpager Scrollview fragment 滑动
- 面试总结CSS HTML
- 射线和三角面的相交判断
- 数据类型、变量和数组
- 最短路径(Shortest Path)
- Go 的基本类型有Basic types
- hdu 5458 树链剖分模板