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.
解法1:
# 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 not t1 and not t2: return None root = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0)) root.left = self.mergeTrees(t1.left if t1 else None, t2.left if t2 else None) root.right = self.mergeTrees(t1.right if t1 else None, t2.right if t2 else None) return root
更简略的:
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
用and代替if明显是代码更少!
官方解答有错,修改了原有的输入数据:
public class Solution { public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { if (t1 == null) return t2; if (t2 == null) return t1; t1.val += t2.val; t1.left = mergeTrees(t1.left, t2.left); t1.right = mergeTrees(t1.right, t2.right); return t1; } }
如果不用递归而使用迭代,采用队列实现,层序遍历BFS思想,当遇到2颗树对应的节点之一不为null时就需入队,同时在建立新树时也一样将对应的结果节点入队:
# 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 """ # solution 2 if not t1 and not t2: return None q1, q2 = collections.deque([t1]), collections.deque([t2]) root = TreeNode(0) q = collections.deque([root]) while q1 and q2: node1, node2, node = q1.popleft(), q2.popleft(), q.popleft() node.val = (node1 and node1.val or 0) + (node2 and node2.val or 0) if (node1 and node1.left) or (node2 and node2.left): q1.append(node1 and node1.left) q2.append(node2 and node2.left) node.left = TreeNode(0) q.append(node.left) if (node1 and node1.right) or (node2 and node2.right): q1.append(node1 and node1.right) q2.append(node2 and node2.right) node.right = TreeNode(0) q.append(node.right) return root
空间复杂度O(max(M,N)), M、N为两颗树的节点个数。
注,关于deque可以直接判断其是否为空:
>>> import collections
>>> q=collections.deque([])
>>> if q:
... print "Y"
...
>>> q=collections.deque([1])
>>> if q:
... print "x"
...
x
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-02-28 elasticsearch function_score Query——文档排序结果的最后一道墙
2017-02-28 矩阵管理——和visitor模式没有本质区别,都是为了避免资源重复
2017-02-28 矩阵管理——本质是职能分工,例如所有部门都执行财务部门制定的财务制度而不会各自为政