My Java Code Could Work on My Computer but not in LeetCode


  • 0
    S

    Here is my solution:

    public class Solution {
    public TreeNode UpsideDownBinaryTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        
        leftToStack(root, stack);
        TreeNode newRoot = stack.pop();
        TreeNode current = newRoot;
        while (!stack.isEmpty()) {
            TreeNode tmp = stack.pop();
            if (tmp.right != null) {
                current.left = tmp.right;
            }
            current.right = tmp;
            current = tmp;
        }
        return newRoot;
    }
    
    private void leftToStack(TreeNode root, Stack<TreeNode> stack) {
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
    }}
    

    The code exceeds time for case {1, 2}, but work on my own computer, what's wrong with my code?


Log in to reply
 

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