Wondering better solution in Java!!!!!!!!!!


  • 0

    I have wrote down initially the following code:

    public TreeNode invertTree (TreeNode root) {
    	if (root != null) {
    		TreeNode tmp = root.left;
    		root.left = root.right;
    		root.right = tmp;
    		invertTree (root.left);
    		invertTree (root.right);
    	}
    	return root;
    }
    

    pretty straight forward in recursion, and beats about 21% java submissions, and I try to optimize it using tail recursion like this:

    public TreeNode invertTree (TreeNode root) {
    	TreeNode tail = root;
    	while (tail != null) {
    		TreeNode tmp = tail.left;
    		tail.left = tail.right;
    		tail.right = tmp;
    		invertTree (tail.left);
    		tail = tail.right;
    	}
    	return root;
    }
    

    And it seems not works, still beats about 21% java submissions, so anyone knows why?


  • 1

    Beating 21% means you're already among those taking 0 ms. What do you expect? You think you can solve it in negative time?


  • 0

    Ummm~ You are good at joking! I didn't understand the Accepted Solutions Runtime Distribution well and you let me know now!


Log in to reply
 

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