Узел бинарного дерева

#python-3.x

#python-3.x

Вопрос:

Учитывая следующий класс;

 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):
  

Комментарии:

1. Пытался решить этот код, но мне нужна помощь, пожалуйста. def compare(a,b):

2. Какой код вы написали?

3. я еще не получил решения, пока нет кода, только вопрос

4. Если вы не попытаетесь что-то предпринять самостоятельно, мы не узнаем, где вы ошиблись, и не сможем вас исправить, но мы не предоставим вам полного ответа, если вы не предпримете никаких попыток самостоятельно

Ответ №1:

Это то, что вы ищете?

 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))
  

Комментарии:

1. Не предоставляйте ответ, по крайней мере, не посмотрев, пытался ли OP что-то предпринять, иначе он ничего не поймет и просто скопирует ваш код

Ответ №2:

enter code here def compare(a, b): #проверка: оба узла пустые => одинаковые деревья enter code here , если (a == None и b == None): enter code here возвращает True

 #check: only one note empty: different trees
  

enter code here elif((a == None и b != None) или (a != None и b == None)):
enter code here возвращает False

 #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))