Java inorder recursive solution without global variant


  • 1
    K
    public class Solution {
        public int kthSmallest(TreeNode root, int k) {
            int[] index = new int[1];
            index[0] = k;
            return inorder(root, index);
        }
        
        public int inorder(TreeNode root, int[] index) {
            if(root == null) return -1;
            int left = inorder(root.left, index);
            if(left != -1) return left;
            index[0]--;
            if(index[0] == 0) return root.val;
            return inorder(root.right, index);
        }
    }
    

Log in to reply
 

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