Leetcode 617 Merge Two Binary Trees 二叉树
题意:
给定两棵树,将两棵树合并成一颗树
输入
Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 输出 合并的树 3 / \ 4 5 / \ \ 5 4 7
方法1不需要提供额外内存,但是时间居然很长
![](https://images2015.cnblogs.com/blog/878843/201706/878843-20170614195635134-1307244968.png)
1 /** 2 * Definition for a binary tree node. 3 * type TreeNode struct { 4 * Val int 5 * Left *TreeNode 6 * Right *TreeNode 7 * } 8 */ 9 func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode { 10 if t1 == nil && t2 == nil{ 11 return nil 12 } 13 if t1 != nil && t2 == nil{ 14 return t1 15 } 16 if t1 == nil && t2 != nil{ 17 return t2 18 } 19 if t1 != nil && t2 != nil{ 20 t1.Val += t2.Val 21 t1.Left = mergeTrees(t1.Left, t2.Left); 22 t1.Right = mergeTrees(t1.Right, t2.Right); 23 } 24 return t1; 25 }
方法2需要提供额外内存,但是时间居然比方法1少,简直不可思议
1 /** 2 * Definition for a binary tree node. 3 * type TreeNode struct { 4 * Val int 5 * Left *TreeNode 6 * Right *TreeNode 7 * } 8 */ 9 func newTreeNode() *TreeNode{ 10 return &TreeNode{ 11 } 12 } 13 14 func dfs(m **TreeNode, t *TreeNode){ 15 16 if t == nil { 17 return ; 18 } 19 20 if (*m) == nil{ 21 (*m) = newTreeNode() 22 } 23 24 (*m).Val += t.Val 25 dfs(&((*m).Left), t.Left) 26 dfs(&((*m).Right), t.Right) 27 28 } 29 30 func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode { 31 if t1 == nil && t2 == nil { 32 return nil 33 } 34 35 m := newTreeNode() 36 37 dfs(&m, t1); 38 dfs(&m, t2); 39 40 return m; 41 }