项目作者: eMahtab

项目描述 :
kth Smallest element in a BST
高级语言:
项目地址: git://github.com/eMahtab/kth-smallest-element-in-a-bst.git
创建时间: 2020-02-06T17:55:17Z
项目社区:https://github.com/eMahtab/kth-smallest-element-in-a-bst

开源协议:

下载


kth Smallest element in a BST

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.

  1. Example 1:
  2. Input: root = [3,1,4,null,2], k = 1
  3. 3
  4. / \
  5. 1 4
  6. \
  7. 2
  8. Output: 1
  9. Example 2:
  10. Input: root = [5,3,6,2,4,null,null,1], k = 3
  11. 5
  12. / \
  13. 3 6
  14. / \
  15. 2 4
  16. /
  17. 1
  18. Output: 3

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?

Implementation :

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public int kthSmallest(TreeNode root, int k) {
  12. List<Integer> list = new ArrayList<>();
  13. inorderTraversal(root, list);
  14. return list.get(k-1);
  15. }
  16. public void inorderTraversal(TreeNode node, List<Integer> list){
  17. if(node != null){
  18. inorderTraversal(node.left, list);
  19. list.add(node.val);
  20. inorderTraversal(node.right, list);
  21. }
  22. }
  23. }

References :

https://www.youtube.com/watch?v=C6r1fDKAW_o