Recursive java solution without any static fields

  • 0
    class Solution {
        class Pair {
            int x;
            int y;
            public Pair (int x, int y) {
                this.x = x;
                this.y = y;
        public int kthSmallest(TreeNode root, int k) {
            return kthSmallestNode(root, k).y;
        private Pair kthSmallestNode (TreeNode root, int k) {
            if (root == null) return new Pair(k, 0);
            Pair left = kthSmallestNode(root.left, k);
            if (left.x == 0) return left;
            int leftK = --left.x;
            if (leftK == 0) return new Pair(0, root.val);
            return kthSmallestNode(root.right, leftK); 

Log in to reply

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