InOrder, O(1) Extra Space, O(k) Time, Beat 95%


  • 0
    W
        private int count = 0;
        private boolean finish = false;
        private int ret = 0;
        private void inOrder(TreeNode root, int k)
        {
            if (root == null || finish)
                return;
            
            inOrder(root.left, k);
            
            count++;
            if (count == k)
            {
                finish = true;
                ret = root.val;
            }
            
            inOrder(root.right, k);
        }
        public int kthSmallest(TreeNode root, int k) 
        {
            inOrder(root, k);
            return ret;
        }
    

Log in to reply
 

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