Java Kth smallest element in BST using queue


  • 0
    V

    public class Solution {

    Queue<TreeNode> q = new LinkedList<TreeNode>();
    
    public int kthSmallest(TreeNode root, int k) {
        inorder(root);
        int result = 0;
        TreeNode tmp = null;
        while(k != 0){
            tmp = q.poll();
            k--;
        }
        
        result = tmp.val;
        return result;
    }
    
    private void inorder(TreeNode root){
        if(root != null){
            inorder(root.left);
            q.offer(root);
            inorder(root.right);
        }
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.