230. 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小的数字
1 private int leftTreeNodeCount(TreeNode root) { 2 if (root == null) return 0; 3 return 1 + leftTreeNodeCount(root.left) + leftTreeNodeCount(root.right); 4 } 5 6 public int kthSmallest(TreeNode root, int k) { 7 // 在二叉搜索树种,找到第K个小的元素。 8 // 算法如下: 9 // 1、计算左子树元素个数left。 10 // 2、 left+1 = K,则根节点即为第K个元素 11 // 3、left >=k, 则第K个元素在左子树中, 12 // 4、left +1 <k, 则转换为在右子树中,寻找第K-left-1元素 13 int leftCount = leftTreeNodeCount(root.left); 14 if (leftCount >= k) { 15 return kthSmallest(root.left, k); 16 } 17 if (leftCount + 1 < k) return kthSmallest(root.right, k - leftCount - 1); 18 return root.val; 19 }