My code can pass on my local environment, my fails the online judge. Anybody can help? thanks

public class Solution {
TreeNode n1 = null;
TreeNode n2 = null;
TreeNode prev = null;

private void inorder(TreeNode node){
    if(node == null) return;
    inorder(node.left);
    if(prev != null && prev.val > node.val) {
        if(n1 == null){
            n1 = prev;
        }
        n2 = node;
    } 
    prev = node;
    inorder(node.right);
}

public void recoverTree(TreeNode root) {
    // Start typing your Java solution below
    // DO NOT write main() function
    if(root == null) return;
    inorder(root);
    if(n1 != null && n2 != null){
        int swap = n1.val;
        n1.val = n2.val;
        n2.val = swap;
    }
}

}

asked 27 May, 09:20

tedcheng's gravatar image

tedcheng
112
accept rate: 0%


Did you notice the notification? I see you have three member variables declared, would it be the root cause?

IMPORTANT: The Solution object is instantiated only once and is reused for each test case input. When declaring a class member variable, be extra cautious and remember to reset the variable!

link

answered 27 May, 20:34

wglacier's gravatar image

wglacier
212
accept rate: 0%

Thanks, that's exactly the reason, I need reset the class variable.

(27 May, 21:10) tedcheng tedcheng's gravatar image
Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • Indent code by 4 spaces.
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×4
×2
×1
×1

Asked: 27 May, 09:20

Seen: 360 times

Last updated: 17 Jul, 01:58