Python,检查变量是否连续被赋予不同的值?

Python, Checking whether the variable is given different values ​in a row?

我需要帮助准备 python 中的小 if 条件。

我有这段代码:(基本的极客二叉树示例)

class Node:
def __init__(self,key):
    self.left = None
    self.right = None
    self.val = key


root = Node(9)

root.left = Node(7)
root.left.left = Node(2)
root.left.left = Node(3)

root.left.right = Node(5)

root.right = Node(8)
root.right.left = Node(7)
root.right.left.right = Node(5)

我想编写一个控制器,当它检测到我在下面列出的部分中覆盖的变量时,它将 return False。

    root.left.left = Node(2)
    root.left.left = Node(3)
    return False

简而言之:

root = Node(9)
root.left = Node(7)
root.left.left = Node(2)
root.left.left = Node(3)
root.left.right = Node(5)
root.right = Node(8)
root.right.left = Node(7)
root.right.left.right = Node(5)
---FALSE---

check_tree(root) = False

###########################################
root2 = Node(9)
root2.left = Node(7)
root2.left.left = Node(2)
root2.left.right = Node(5)
root2.right = Node(8)
root2.right.left = Node(7)
root2.right.left.right = Node(5)
---TRUE---

check_tree(root2) = True

提前感谢所有愿意花时间帮助我的人:)

如果您知道要在何处插入节点,这应该可以工作。 Returns该位置的节点值,是否为新节点插入。

#Where traversalOrder is your place of insertion (ex. root.right.left)
#and nodeVal is the value you wish to insert into the tree
def traverse(traversalOrder, nodeVal):
    #If there is a value at the given location within the tree,
    #Return false and node val currently there
    if traversalOrder != None:
        return False, traversalOrder.val
    #insert the value otherwise
    traversalOrder = Node(nodeVal)
    #Else, return true and the new inserted val
    return True, nodeVal

每次尝试插入新节点时都可以运行此方法。