230. Kth Smallest Element in a BST

T: O(k)

S: O(n)

/**
 * 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 {
    public int kthSmallest(TreeNode root, int k) {
        int[] result = new int[1];
        int[] rank = new int[1];
        dfs(root, k, rank, result);
        return result[0];
    }
    private void dfs(TreeNode node, int k, int[] rank, int[] result) {
        if (node == null) {
            return;
        }
        dfs(node.left, k, rank, result);
        rank[0]++;
        if (rank[0] == k) {
            result[0] = node.val;
            return;
        }
        dfs(node.right, k, rank, result);
    }
}

Last updated