230. Kth Smallest Element in a BST
来源:互联网 发布:淘宝上找不到一淘网 编辑:程序博客网 时间:2024/05/17 03:35
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?
Hint:
- Try to utilize the property of a BST.
- What if you could modify the BST node's structure?
- The optimal runtime complexity is O(height of BST).
直接中序遍历,第K个访问到的即是所求。
int cnt;int ret=0;public int kthSmallest(TreeNode root, int k){if(root!=null)inorder(root, k);return ret;}private void inorder(TreeNode t,int k){if(t.left!=null)inorder(t.left, k);cnt++;if(cnt==k){ret=t.val;return ;}if(t.right!=null)inorder(t.right, k);}
-----------------------------------------------------------------
O(height of BST).的方法
https://leetcode.com/discuss/43771/implemented-java-binary-search-order-iterative-recursive
public int kthSmallest(TreeNode root, int k) { int count = countNodes(root.left); if (k <= count) { return kthSmallest(root.left, k); } else if (k > count + 1) { return kthSmallest(root.right, k-1-count); // 1 is counted as current node } return root.val; } public int countNodes(TreeNode n) { if (n == null) return 0; return 1 + countNodes(n.left) + countNodes(n.right); }
0 0
- 230.Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 以太坊客户端mist和geth加快区块同步速度的方法
- 数据结构复习之二叉树(3)
- TCP/IP详解--几类定时器的作用(重传 保活定时器)
- android 调用系统的照相机和图库实例详解
- 解读 CSS 布局之水平垂直居中
- 230. Kth Smallest Element in a BST
- Swift 初见(A Swift Tour)
- C语言基础 矩形法求矩阵积分
- Adapter类控件使用之ExpandableList(可折叠式列表)的基本使用
- Robolectric
- java并发之Fork/Join实例
- C语言基础 从键盘输入一些数据,从中找出最小值及其位置
- 矩阵中的路径
- 【牛腩新闻发布系统】——SQL注入