Напишите функцию, которая принимает бинарное дерево и переворачивает ее.
tree = 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9
tree = 1 / \ 3 2 / \ / \ 7 6 5 4 / \ 9 8
def invert_binary_tree(tree): queue = [tree] while len(queue) > 0: cur_node = queue.pop(0) if cur_node is not None: cur_node.left, cur_node.right = cur_node.right, cur_node.left queue.append(cur_node.left) queue.append(cur_node.right) return tree # This is the class of the input binary tree. class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None
- Сначала переверните корневой узел дерева.
- Переверните левого ребенка с правым ребенком.
- Продолжайте заменять ребенка последующего узла.
- Выполните проходную дорогу.
- Используйте очередь, чтобы выполнить обход итеративно.
- AlgoExpert для заявления о проблеме.
- Томас Робертсон для обложки ( https://unsplash.com/photos/wakld_0lcma ).
Оригинал: “https://dev.to/anzhari/today-i-learned-invert-binary-tree-hcj”