LeetCode:617. Merge Two Binary Trees
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:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
Note: The merging process must start from the root nodes of both trees.
意思就是合并两个二叉树,某个位置同时存在节点则节点值变为两个节点值之和,否则直接合并。
思路一:递归
如果两棵树的某个位置的子节点都不为空,则递归合并该子节点,否则统一合并到第一棵树上。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if (t1 != None and t2 != None):
t1.val = t1.val+t2.val
if (t1.left != None and t2.left != None):
self.mergeTrees(t1.left,t2.left)
if (t1.right != None and t2.right != None):
self.mergeTrees(t1.right,t2.right)
if (t1.right == None and t2.right != None):
t1.right = t2.right
if (t1.left == None and t2.left != None ):
t1.left = t2.left
if (t1 == None and t2 != None):
t1 = t2
return t1
思路二:循环的方法
借助一个辅助栈,同时遍历两棵树,每次将非空节点压入栈中,同时从顶部取出之后遍历左右子树。
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if (t1 == None):
return t2
stack = []
stack.append([t1, t2])
while (len(stack) > 0):
t = stack.pop()
if (t[0] == None or t[1] == None) :
continue
t[0].val += t[1].val
if (t[0].left == None):
t[0].left = t[1].left
else:
stack.append([t[0].left, t[1].left])
if (t[0].right == None):
t[0].right = t[1].right
else:
stack.append([t[0].right, t[1].right])
return t1;
THE END.