Inspired by BST iterator


  • 0
    S

    the below code is inspired by BST iterator

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

Log in to reply
 

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