题目要求:
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.
题目分析:
合并二棵树,其实就是遍历的问题,采用先序遍历,先访问根结点,然后访问左子结点,右子结点,采用递归的方式来实现,对于递归肯定是有结束的判断,对于结束的条件返回什么比较合算,需要在不同的题中,不同的分析。在本题中,结束返回的是处理完的那个节点,然后之前的结点的左子结点,右子结点就可以为其赋值,达到想要的结果。
python代码的实现:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 != None and t2 != None:
t1.val = t1.val + t2.val
if t1 == None and t2 != None:
return t2
if t1 != None and t2 == None:
return t1
if t1 == None and t2 == None:
return t1
t1_l = t1.left
t2_l = t2.left
node = self.mergeTrees(t1_l, t2_l)
t1.left = node
t1_r = t1.right
t2_r = t2.right
node = self.mergeTrees(t1_r, t2_r)
t1.right = node
return t1
再重新写一遍程序,发现之前的只是实现功能,改变了原有的树的结构,这并不是我们愿意看到的景象,所以,应该是新建节点,然后建立新的树。其实下面的代码也是改变了结构,改了不相匹配的节点(一个为空,一个不为空,改变了不为空的那个节点)
python代码:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 and t2:
new_node = TreeNode(t1.val + t2.val)
new_node.left = self.mergeTrees(t1.left, t2.left)
new_node.right = self.mergeTrees(t1.right, t2.right)
return new_node
return t1 or t2
先来看看大神们是怎么做的。大佬真的是厉害,通过判断,为空的变化为0来做,然后就可以把语句整合到一起了。
def mergeTrees(self, t1, t2):
if not t1 and not t2: return None
ans = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0))
ans.left = self.mergeTrees(t1 and t1.left, t2 and t2.left)
ans.right = self.mergeTrees(t1 and t1.right, t2 and t2.right)
return ans
我刚刚一晃神,以为是自己写的程序,,哇,原来也是之前复制粘贴大佬的程序,居然跟我写的一样,尴尬,保证没有抄袭。。
class Solution(object):
def mergeTrees(self, t1, t2):
if t1 and t2:
root = TreeNode(t1.val + t2.val)
root.left = self.mergeTrees(t1.left, t2.left)
root.right = self.mergeTrees(t1.right, t2.right)
return root
else:
return t1 or t2
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if not t1 and not t2: return None
if t1:
v1, L1, R1 = t1.val, t1.left, t1.right
else:
v1, L1, R1 = 0, None, None
if t2:
v2, L2, R2 = t2.val, t2.left, t2.right
else:
v2, L2, R2 = 0, None, None
node = TreeNode(v1+v2)
node.left = self.mergeTrees(L1, L2)
node.right = self.mergeTrees(R1, R2)
return node
大佬另辟蹊径,然后把类别分出来,然后依据类别进行选择。。。666.