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?
利用BST的中序遍历就是排序数组的性质。找第k大,那就中序遍历+cnt,当cnt到了第k个的时候停止遍历即可。中序遍历要点(node和stack条件或;左推到底;吐一个;等于右)
Follow up:在树的设计里维护一个int记录节点下面结点总个数。找第k大用递归。当左结点个数>=k大,那就在左子树找;当左节点个数== k-1<那就是当前结点的值;当左结点个数 < k -1,那就去右子树找。(另外最前面注意检查下左结点是不是null,是的话那就直接找当前或右子树。)
实现本题:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int kthSmallest(TreeNode root, int k) { int cnt = 0; TreeNode node = root; Stack<TreeNode> stack = new Stack<>(); int result = 0; while (cnt < k) { while (node != null) { stack.push(node); node = node.left; } node = stack.pop(); result = node.val; cnt++; node = node.right; } return result; } }
实现follow up:(credit to leetcode discussion)
public class Solution { public int kthSmallest(TreeNode root, int k) { TreeNodeWithCount rootWithCount = buildTreeWithCount(root); return kthSmallest(rootWithCount, k); } private TreeNodeWithCount buildTreeWithCount(TreeNode root) { if (root == null) return null; TreeNodeWithCount rootWithCount = new TreeNodeWithCount(root.val); rootWithCount.left = buildTreeWithCount(root.left); rootWithCount.right = buildTreeWithCount(root.right); if (rootWithCount.left != null) rootWithCount.count += rootWithCount.left.count; if (rootWithCount.right != null) rootWithCount.count += rootWithCount.right.count; return rootWithCount; } private int kthSmallest(TreeNodeWithCount rootWithCount, int k) { if (k <= 0 || k > rootWithCount.count) return -1; if (rootWithCount.left != null) { if (rootWithCount.left.count >= k) return kthSmallest(rootWithCount.left, k); if (rootWithCount.left.count == k-1) return rootWithCount.val; return kthSmallest(rootWithCount.right, k-1-rootWithCount.left.count); } else { if (k == 1) return rootWithCount.val; return kthSmallest(rootWithCount.right, k-1); } } class TreeNodeWithCount { int val; int count; TreeNodeWithCount left; TreeNodeWithCount right; TreeNodeWithCount(int x) {val = x; count = 1;}; } }