I am seriously wondering about getting rid of the first while loop.


  • 0
    M

    I am seriously wondering about getting rid of the first while loop.

    I tried my best to consolidate the first while loop into the second while loop which is what actually get things done. In that way, I can get the correct answer without redundant code, since there is one part in the second while loop does the same job as the while loop outside it. But I just ended up with a quite similar answer showing below.

    public int kthSmallest(TreeNode root, int k) {

    Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        TreeNode it = root;
        
         while(it != null)
        {
            stack.push(it);
            it = it.left;
        }
        
        while(true){//Time Limit Exceeded
                it = stack.pop();
                k--;
                if(k == 0) return it.val;
                if(it.right != null){
                    stack.push(it.right);
                    it = it.right;
                    
                     while(it.left != null)
                    {
                        it = it.left;
                        stack.push(it);
                    }
                }
            
        }
    }

  • 0
    S

    https://leetcode.com/discuss/64251/ac-python-76ms-iterative-clean-solution maybe you'll be interested in this (although it's in Python).


Log in to reply
 

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