11 Lines Java Code with a Fake Pass By Reference

  • 0

    Becuase Java does not have pass by reference so we use an array to pass count in the recursion.

    public int kthSmallest(TreeNode root, int k) {
            return dfs(root, new int[]{k}); 
        private int dfs(TreeNode root, int[] k) { 
        	if(root == null) return 0; 
        	int res = dfs(root.left, k); 
        	if(k[0] == 0) return res; 
        	if(--k[0] == 0) return root.val; 
        	return dfs(root.right, k);

Log in to reply

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