❝
The original address: https://leetcode-cn.com/problems/merge-two-binary-trees/ the original link: https://juejin.cn/post/6877184981626519565
❞
The title
Given two binary trees, imagine that when you overlay one of them on top of the other, some nodes of the two binary trees will overlap. You need to merge them into a new binary tree. The rule for merging is that if two nodes overlap, their values are added as the new value of the nodes merged, otherwise a node that is not NULL is directly added as a node in the new binary tree.
Example 1:
Input: Tree 1 Tree 2
1 2
/ \ \ 3 2 1 3
/ \ \ 5, 4, 7Output:Merged tree: 3 / \ 4, 5 / \ \ 5, 4, 7Copy the code
Note: The merge must start at the root of both trees.
Their thinking
- for
! t1 && ! t2
returnnull
- for
t1 && ! t2
returnt1
- for
! t1 && t2
returnt2
- for
t1 && t2
,t1.val = t1.val + t2.val
- recursive
/ * * * Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null; *}* / / * * * @param {TreeNode} t1 * @param {TreeNode} t2 * @return {TreeNode} * / var mergeTrees = function(t1, t2) { if(! t1 && ! t2) { return null } if(t1 && ! t2) { return t1 } if(! t1 && t2) { return t2 } t1.val = t1.val + t2.val t1.left = mergeTrees(t1.left, t2.left) t1.right = mergeTrees(t1.right, t2.right) return t1 }; Copy the code