Anyone can help me check what's wrong?

  • 0

    I tested code below in eclipse, it works fine for the case "2, #, 1", but it can't pass for OJ, any pointer will be appreciated.

    public class Solution {
    private static boolean bLookForFirst = true;
    private static TreeNode last, first, second; //last is the last node visited, first and second are the swapped node
    public void recoverTree(TreeNode root) {
        if (first != null && second != null) { //swap val
            int val = first.val;
            first.val = second.val;
            second.val = val;
    private void traverseTree(TreeNode n) {
        if (n == null) return;
        if (last != null) {
            if (last.val > n.val) {
                if (bLookForFirst) {
                    first = last;
                    second = n; // for current is last node case, otherwise, second will be overriden
                    bLookForFirst = false;
                else {
                    second = n;
        last = n;


  • 0

    Since LeetCode run all test case in once, it won't work if there is some static variable like private static boolean bLookForFirst = true;.

Log in to reply

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