Skip to content

Latest commit

 

History

History
91 lines (79 loc) · 2.82 KB

617. 合并二叉树 - Easy.md

File metadata and controls

91 lines (79 loc) · 2.82 KB

给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。

你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。

示例 1:

输入: 
	Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
输出: 
合并后的树:
	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7

注意: 合并必须从两个树的根节点开始。

Solution

递归解法

  1. 可以使用前序、中序、后序的方法完成遍历
# 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 not t1 and not t2:
            return None
        elif not t1:
            return t2
        elif not t2:
            return t1
        else:
            t1.val += t2.val
            t1.left = self.mergeTrees(t1.left, t2.left)
            t1.right = self.mergeTrees(t1.right, t2.right)
            return t1
        

非递归解法

  1. 层次遍历,使用栈存储待遍历节点;准确地说,是存储需要合并的节点pair
  2. 与常规循环遍历不同的是,存储的是tuple而不是单个元素/节点
  3. n1, n2 = stack.pop()也可以改为n1, n2 = stack.pop(0),只是处理的顺序有所区别
# 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 not t1 or not t2:
            return t1 or t2
        else:
            stack = [(t1, t2)]
            while stack:
                n1, n2 = stack.pop()
                n1.val += n2.val
                if n1.left:
                    if n2.left:
                        stack.append((n1.left, n2.left))
                else:
                    if n2.left:
                        n1.left = n2.left

                if n1.right:
                    if n2.right:
                        stack.append((n1.right, n2.right))
                else:
                    if n2.right:
                        n1.right = n2.right

            return t1