0

For this question on leet code, this code is passing all the test cases.

class Solution(object):
def recoverTree(self, root):
    self.first = None
    self.second = None
    self.prev = TreeNode(float('-inf'))

    self.traverse(root)

    temp = self.first.val
    self.first.val = self.second.val
    self.second.val = temp

def traverse(self, root):
    if not root:
        return
    self.traverse(root.left)
    if not self.first and self.prev.val >= root.val:
        self.first = self.prev
    if self.first and self.prev.val >= root.val:
        self.second = root
    self.prev = root
    self.traverse(root.right)

I have a question about one part of this code.

if not self.first and self.prev.val >= root.val:
    self.first = self.prev
if self.first and self.prev.val >= root.val:
    self.second = root

In this snippet, wont the second condition always be true after the first one has been set. So, you coud write it as:

def not self.first and self.prev.val >= root.val:
    self.first = self.prev
    self.second = root

But if I try this, I will not pass the test cases. Why is it the case? It seem like if we accept the condition for first if statement, and assign self.first, condition for second if statement will always be true. But in reality this seems not to be the case. Can someone please explain whats happening here?

user3408657
  • 179
  • 1
  • 3
  • 13
  • There's no not in the second if statement – Natecat Oct 12 '16 at 04:30
  • @Natecat but if the first if statement is true, as in self.first is None, then when we go into the statement we set self.first = self.prev, then self.First is no longer None, and the condition for the second if statement will always be true. – user3408657 Oct 12 '16 at 05:10

1 Answers1

0

The code is different because you still want to run self.second = root. You want to run this line whether self.first was true or false before you started playing with it.

Likely there is a test in which self.first is true and the expected outcome is that self.second == root.

Vikram Saran
  • 1,143
  • 8
  • 17