LeetCode:617. Merge Two Binary Trees

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.

意思就是合并两个二叉树,某个位置同时存在节点则节点值变为两个节点值之和,否则直接合并。

思路一:递归

如果两棵树的某个位置的子节点都不为空,则递归合并该子节点,否则统一合并到第一棵树上。

Python 代码实现

# 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值