Kth Smallest Element in a BST

lc 230

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.

Inorder Traversal o(n)

public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        if(root == null) return 0;
        int count = 0 ;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        while(root != null || ! stack.isEmpty()){
            while(root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            count++;
            if(count == k) return root.val;
            root = root.right;
        }
        return 0;
    }
}

results matching ""

    No results matching ""