【问题标题】:Python, Checking whether the variable is given different values ​in a row?Python,检查变量是否连续被赋予不同的值?
【发布时间】:2020-05-03 21:31:30
【问题描述】:

我需要帮助在 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

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

【问题讨论】:

    标签: python class if-statement tree binary-tree


    【解决方案1】:

    如果您知道要在哪里插入节点,这应该可以工作。返回该位置的节点值以及是否是新节点插入。

    #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
    

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

    【讨论】:

    • 谢谢,这段代码完美运行。但我需要这样的东西: - 假设我们创建 root1,root1 中的所有内容都是正确的(没有重叠的节点。)并创建另一个根 root2。使用 root2 我们有重复的节点分配。我需要这样的东西:check_tree(root1) = True, check_tree(root2) = False
    • 运行树遍历并从根开始跟踪您的路径。如果您能够到达该路径,则您知道那里有一个先前的值,因此您可以返回 false。否则,它将返回 true,然后您可以将节点插入该位置。
    猜你喜欢
    • 1970-01-01
    • 2023-01-07
    • 2020-01-09
    • 2010-11-15
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 2021-09-18
    • 2022-11-22
    相关资源
    最近更新 更多