230. Kth Smallest Element in a BST

中序遍历设置计数器

int count = 0;
int result = 0;

public int kthSmallest(TreeNode root, int k) {
    dfs(root, k);
    return result;
}

public void dfs(TreeNode root, int k) {
    if (root == null) return;
    dfs(root.left, k);
    count++;
    if (count == k) result = root.val;
    if (count < k) dfs(root.right, k);
}

results matching ""

    No results matching ""