[LeetCode] 617. Merge Two Binary Trees

旧城冷巷雨未停 提交于 2020-01-21 03:13:24

合并两个二叉树。题意是给两个二叉树,请按照node的位置对应合并两个二叉树。如果两个二叉树在同一个位置都有各自的node,就对两个node的值相加。例子,

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

两种解法,BFS和DFS。DFS解法会用到递归,先序遍历的思路做。

时间O(n)

空间O(n)

 1 /**
 2  * @param {TreeNode} t1
 3  * @param {TreeNode} t2
 4  * @return {TreeNode}
 5  */
 6 var mergeTrees = function (t1, t2) {
 7     // corner case
 8     if (t1 === null && t2 === null) {
 9         return null;
10     }
11     if (t1 === null || t2 === null) {
12         return t1 || t2;
13     }
14 
15     // normal case
16     var root = new TreeNode(t1.val + t2.val);
17     root.left = mergeTrees(t1.left, t2.left);
18     root.right = mergeTrees(t1.right, t2.right);
19     return root;
20 };

 

BFS的做法会用到层序遍历,依然还是一个一个node扫描。

时间O(n)

空间O(n)

 1 /**
 2  * @param {TreeNode} t1
 3  * @param {TreeNode} t2
 4  * @return {TreeNode}
 5  */
 6 var mergeTrees = function (t1, t2) {
 7     // corner case
 8     if (t1 === null) return t2;
 9     if (t2 === null) return t1;
10 
11     // normal case
12     let stack = [];
13     stack.push([t1, t2]);
14     while (stack.length) {
15         let cur = stack.pop();
16         if (cur[0] === null || cur[1] === null) {
17             continue;
18         }
19         cur[0].val += cur[1].val;
20         if (cur[0].left === null) {
21             cur[0].left = cur[1].left;
22         } else {
23             stack.push([cur[0].left, cur[1].left]);
24         }
25         if (cur[0].right === null) {
26             cur[0].right = cur[1].right;
27         } else {
28             stack.push([cur[0].right, cur[1].right]);
29         }
30     }
31     return t1;
32 };
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!