123 - 617 合并二叉树
Last updated
Was this helpful?
Last updated
Was this helpful?
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例 1:
输入: Tree 1 Tree 2 1 2 / / \ 3 2 1 3 / \ 5 4 7
输出: 合并后的树: 3 / 4 5 / 5 4 7
注意: 合并必须从两个树的根节点开始。
感觉需要遍历两个二叉树,同时新建一个新的二叉树
看了题解之后发现,并不用那么麻烦,只需要递归修改t1就行了
Runtime: 104 ms, faster than 12.56% of JavaScript online submissions for Merge Two Binary Trees.
Memory Usage: 40.2 MB, less than 84.62% of JavaScript online submissions for Merge Two Binary Trees.
Runtime: 84 ms, faster than 87.65% of Python3 online submissions for Merge Two Binary Trees.
Memory Usage: 14.3 MB, less than 20.00% of Python3 online submissions for Merge Two Binary Trees.
python里面没有null,只用None,而且判断的方法几乎就是英文。。😂😂
Runtime: 28 ms, faster than 88.85% of Go online submissions for Merge Two Binary Trees.
Memory Usage: 8.8 MB, less than 100.00% of Go online submissions for Merge Two Binary Trees.