Recover Binary Tree
<p>For <a href="https://leetcode.com/problems/recover-binary-search-tree/" rel="nofollow" title="this">this</a> question on leet code, this code is passing all the test cases. </p>

<pre><code>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 &gt;= root.val:
        self.first = self.prev
    if self.first and self.prev.val &gt;= root.val:
        self.second = root
    self.prev = root
    self.traverse(root.right)
</code></pre>

<p>I have a question about one part of this code.</p>

<pre><code>if not self.first and self.prev.val &gt;= root.val:
    self.first = self.prev
if self.first and self.prev.val &gt;= root.val:
    self.second = root
</code></pre>

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

<pre><code>def not self.first and self.prev.val &gt;= root.val:
    self.first = self.prev
    self.second = root
</code></pre>

<p>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?</p>

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

<p>Likely there is a test in which <code>self.first</code> is <code>true</code> and the expected outcome is that <code>self.second == root</code>.</p>

python if-statement recursion binary-search-tree traversal