CCmonitor
CCmonitor
2018-01-04 02:52
采纳率: 60%
浏览 909
已采纳

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

求C#大神,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条回答 默认 最新

  • caozhy
    已采纳
     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;
    }
    手写的,你参考下
    
    点赞 评论
  • bdmh
    bdmh 2018-01-04 02:59

    你指什么调用,首先你要有两个二叉树,然后把两个树的根节点节点传入MergeTrees

    点赞 评论
  • ljheee
    ljheee 2018-01-04 04:53

    用节点数少的那个树,一个个把节点插入另一个树

    点赞 评论
  • qq_36715799
    qq_36715799 2018-01-04 05:55

    你指什么调用,首先你要有两个二叉树,然后把两个树的根节点节点传入MergeTrees的呀

    点赞 评论
  • weixin_35889315
    weixin_35889315 2018-01-04 06:12

    用节点数少的那个树,一个个把节点插入另一个树。

    点赞 评论

相关推荐