CCmonitor 2018-01-04 02:52 采纳率: 0%

# LeetCode 617. Merge Two Binary Trees 怎么实现调用

class Program
{
static void Main(string[] args)
{
TreeNode tree = new TreeNode(1);
Program p = new Program();
tree.val = 1;
TreeNode t1;
t1.val = 1;
TreeNode t2;
t2.val = 2;

``````        //TreeNode t1 = { 1, 3, 2, 5 };
//TreeNode t2 = new TreeNode{2, 1, 3, null, 4, null, 7};
p.MergeTrees(t1, t2);
}

public TreeNode MergeTrees(TreeNode t1, TreeNode t2)
{
if (t1 == null && t2 == null)
{
return null;
}
if (t1 != null && t2 == null)
{
return t1;
}
if (t1 == null && t2 != null)
{
return t2;
}
if (t1 != null && t2 != null)
{
t1.val += t2.val;
t1.left = MergeTrees(t1.left, t2.left);
t1.right = MergeTrees(t1.right, t2.right);
}
return t1;
}
}

public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
public int valprop {
get { return val;}
set { }
}
}
``````
• 写回答

#### 5条回答默认 最新

• threenewbee 2018-01-04 03:34
关注
`````` int?[] arr = {new int?(1),new int?(2),new int?(3),new int?(5)};
TreeNode t = buildtree(arr, 0);

TreeNode BuildTree(int?[] arr, int pos)
{
TreeNode t = new TreeNode(arr[pos]);
if (arr.Length > pos * 2 +1) t.Left = BuildTree(arr, pos * 2 + 1);
if (arr.Length > pos * 2 +2) t.Right = BuildTree(arr, pos * 2 + 2);
return t;
}
手写的，你参考下
``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 python结合Matlab仿真忆阻器
• ¥35 有人会注册whatsaop协议号吗？