What is the problem with the if statement in python?

I"m doing a leetcode problem and giving a search tree. Two nodes are given to find the nearest common parent node.
the title is easy. I wrote it this way

"

def lowestCommonAncestor(self, root, p, q):
    """
    :type root: TreeNode
    :type p: TreeNode
    :type q: TreeNode
    :rtype: TreeNode
    """
    while root:
        if root.val > p.val and root.val > q.val:
            root = root.left
        if root.val < p.val and root.val < q.val:
            root = root.right
        else:
            return root

"
but it didn"t pass, because I used if.if. Else.
and then I tried to change it to if.elif.else.
and it passed smoothly. I wondered if the two ways of writing on this question should turn out to be the same. How could I be wrong?

Mar.06,2021

when root.val > p.val and root.val > q.val, the first if is executed, but the root value is changed, but the second if will still be compared, the second if or else will certainly be executed, and the final result will be different.

can be changed like this (add a return):

The structure of
  

if if else is logically different from that of if elseif else. When the first if is satisfied, the first method of writing may be executed to the else direct return, and the second type enters the second loop and continues to follow the logic.

Menu