题目链接: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?
Hint:
public int kthSmallest(TreeNode root, int k) { List<Integer> list = new ArrayList<Integer>(); list = inOrder(root, list); return list.get(k - 1); } public List<Integer> inOrder(TreeNode p, List<Integer> order) { if (p != null) { order = inOrder(p.left, order); order.add(p.val); order = inOrder(p.right, order); } return order; }
int count = 0, result; public int kthSmallest(TreeNode root, int k) { if (root != null) { kthSmallest(root.left, k); count++; if (count == k) { result = root.val; } kthSmallest(root.right, k); } return result; }
class newTreeNode { // BST newTreeNode left, right; int val, leftCount;// 记录左孩子个数 newTreeNode(int val) { this.val = val; } }
int result; public int kthSmallest(newTreeNode root, int k) { if (root != null) { if (root.leftCount + 1 == k) { result = root.val; } else if (root.leftCount + 1 < k) { kthSmallest(root.right, k - (root.leftCount + 1)); } else { kthSmallest(root.left, k); } } return result; }