python 怎么实现两个二叉树合并
问题:给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。输入: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 输出: 合并后的树: 3 / \ 4 5 / \ \ 5 4 7实现:
# Definition for a binary tree node.
class Node(object):
def __init__(self, x):
self.data = x
self.left = None
self.right = None
class Tree(object):
lis = [] # 依次存放左右孩子未满的节点
def __init__(self):
self.root=None
def add(self,x):
node = Node(x)
if self.root == None:
self.root = node
Tree.lis.append(self.root)
else:
while True:
point = Tree.lis
if point.left == None:
point.left = node
Tree.lis.append(point.left)
return
elif point.right == None:
point.right = node
Tree.lis.append(point.right)
Tree.lis.pop(0)
return
class Solution(object):
def mergeTrees(self, t1, t2):
if t1 != None and t2 != None:
t1.data += t2.data
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1
return t1 if t2 is None else t2
t1 = Tree()
t2 = Tree()
L1 =
L2 =
for x in L1:
t1.add(x)
for x in L2:
t2.add(x)
print(t1)
print(t2)
s = Solution()
t = s.mergeTrees(t1,t2)
print(t)
请问下我这样实现问题处在哪里?
如果要调用Solution类应该怎么实现?
页:
[1]