欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

617. Merge Two Binary Trees

程序员文章站 2022-06-03 14:05:46
...

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Example 1:
617. Merge Two Binary Trees


题解:

class BTNode:
    def __init__(self, value):
        self.value = value
        self.lchild = None
        self.rchild = None


def merge(root1, root2):
    if not root1 and not root2:
        return None

    if not root1:
        return root2

    if not root2:
        return root1

    root = BTNode(root1.value + root2.value)
    root.lchild = merge(root1.lchild, root2.lchild)
    root.rchild = merge(root1.rchild, root2.rchild)
    return root


def inorder_traversal(root):
    if not root:
        return

    inorder_traversal(root.lchild)
    print(root.value, end=' ')
    inorder_traversal(root.rchild)


if __name__ == '__main__':
    root1 = BTNode(1)
    root1.lchild = BTNode(3)
    root1.rchild = BTNode(2)
    root1.lchild.lchild = BTNode(5)

    root2 = BTNode(2)
    root2.lchild = BTNode(1)
    root2.rchild = BTNode(3)
    root2.lchild.rchild = BTNode(4)
    root2.rchild.rchild = BTNode(7)

    root = merge(root1, root2)
    inorder_traversal(root)
    print()

相关标签: merge binary tree