Share a clean Java 1ms Solution using an inorder search


  • 0
    A
    public class Solution {
        public int kthSmallest(TreeNode root, int k) {
            int[] kth = new int [1];
            int[] kValue = new int [1];
            helper (root, k, kth, kValue);
            return kValue[0];
        }
        public void helper (TreeNode n, int k, int[] kth, int[] kValue) {
            if (n==null)
                return;
            // left
            if (n.left != null) 
                helper (n.left, k, kth, kValue);
            
            // parent
            if (kth[0]==k)
                return;
            kth[0]++;
            kValue[0] = n.val;
            if (kth[0] == k) {
                return;
            }
            
            // right
            if (n.right != null)
                helper (n.right, k, kth, kValue);
        }
    }

Log in to reply
 

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