给你两棵二叉树: root1 和 root2 。
想象一下,当你将其中一棵覆盖到另一棵之上时,两棵树上的一些节点将会重叠(而另一些不会)。你需要将这两棵树合并成一棵新二叉树。合并的规则是:如果两个节点重叠,那么将这两个节点的值相加作为合并后节点的新值;否则,不为 null 的节点将直接作为新二叉树的节点。
返回合并后的二叉树。
注意: 合并过程必须从两个树的根节点开始。
You are given two binary trees root1 and root2.
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 the two trees 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 the new tree.
Return the merged tree.
Note: The merging process must start from the root nodes of both trees.
示例 1:
输入:root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
输出:[3,4,5,5,4,null,7]
示例 2:
输入:root1 = [1], root2 = [1,2]
输出:[2,2]
提示:
- 两棵树中的节点数目在范围 [0, 2000] 内
- -104 <= Node.val <= 104
可以使用深度优先搜索合并两个二叉树。从根节点开始同时遍历两个二叉树,并将对应的节点进行合并。
- 两个二叉树的对应节点可能存在以下三种情况,对于每种情况使用不同的合并方式。
- 如果两个二叉树的对应节点都为空,则合并后的二叉树的对应节点也为空;
- 如果两个二叉树的对应节点只有一个为空,则合并后的二叉树的对应节点为其中的非空节点;
- 如果两个二叉树的对应节点都不为空,则合并后的二叉树的对应节点的值为两个二叉树的对应节点的值之和,此时需要显性合并两个节点。
先序遍历
var mergeTrees = function(root1, root2) {
if(root1==null) return root2
if(root2==null) return root1
root1.val+=root2.val
root1.left=mergeTrees(root1.left,root2.left)
root1.right=mergeTrees(root1.right,root2.right)
return root1
};
中序遍历
var mergeTrees = function(root1, root2) {
if(root1==null) return root2
if(root2==null) return root1
root1.left=mergeTrees(root1.left,root2.left)
root1.val+=root2.val
root1.right=mergeTrees(root1.right,root2.right)
return root1
};
后序遍历
var mergeTrees = function(root1, root2) {
if(root1==null) return root2
if(root2==null) return root1
root1.left=mergeTrees(root1.left,root2.left)
root1.right=mergeTrees(root1.right,root2.right)
root1.val+=root2.val
return root1
};
leetcode:https://leetcode-cn.com/problems/merge-two-binary-trees/