python - Python,检查变量是否连续被赋予不同的值?
问题描述
我需要帮助在 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)
我想编写一个控制器,当它检测到我在下面列出的部分中覆盖的变量时将返回 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
提前感谢所有愿意花时间帮助我的人:)
解决方案
如果您知道要在哪里插入节点,这应该可以工作。返回该位置的节点值以及是否是新节点插入。
#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
每次尝试插入新节点时都可以运行此方法。