Question
Given the root
of a binary search tree, and an integer k
, return the kth
smallest value (1-indexed) of all the values of the nodes in the tree.
Constraints:
- The number of nodes in the tree is
n
. 1 <= k <= n <= 104
0 <= Node.val <= 104
Algorithm
This question is much similar to the question of BST iterator but a little bit easier. We only need to record the index of current number and pop the right one when the index == k, no matter you are using recursive or iterative way.
Code
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { int res; List<Integer> list = new ArrayList<>(); public int kthSmallest(TreeNode root, int k) { helper(root, k); return res; } private void helper(TreeNode root, int k) { if (root == null) return; helper(root.left, k); list.add(root.val); if (list.size() == k) { res = list.get(list.size() - 1); return ; } helper(root.right, k); } }
There is no need to store the list, a count is enough.
class Solution { int res; int count; public int kthSmallest(TreeNode root, int k) { res = 0; count = k; helper(root); return res; } private void helper(TreeNode root) { if (root == null) return; helper(root.left); count--; if (count == 0) { res = root.val; } helper(root.right); } }