二叉树节点



给定以下类;

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

完成功能

def binary_tree_compare(a, b)
# return True if the two binary trees rooted and a and b are equal in value and structure
# return False otherwise
def compare(a, b):

这是你要找的吗?

def compare(a, b):
    #check: both nodes empty => same trees
    if(a == None and b == None):
        return True
    #check: only one note empty: different trees
    elif((a == None and b != None) or (a != None and b == None)):
        return False
    #check: node content is the same and all children are the same: same tree
    else:
        return (a.val == b.val) and (compare(a.left, b.left) and compare(a.right, b.right))
tmp_node1 = TreeNode("tmp")
tmp_node2 = TreeNode("tmp")
a = TreeNode("something", left=tmp_node1)
b = TreeNode("something", left=tmp_node2)
c = TreeNode("somthing else")
print(compare(a,b))
print(compare(a,c))

enter code here def compare(a, b(: #check:两个节点都为空 => 相同的树 enter code here if(a == None and b == None(: enter code here返回真

#check: only one note empty: different trees
enter code here elif((a == None and b != None(

或 (a != None and b == None((: enter code here返回假

#check: node content is the same and all children are the same: same tree
`enter code here`else:
   `enter code here` return (a.val == b.val) and (compare(a.left, b.left) and compare(a.right, b.right))

最新更新