LeetCode 617. Merge Two Binary Trees

miltonsun · · 805 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

题目

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

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

Note: The merging process must start from the root nodes of both trees.

答案:

golang版是自己写的,其他的是引用cain_huang 的,文末附上链接

golang版,附带测试

mergeTrees.go

package _617_mergeTrees

import "fmt"

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
type TreeNode struct {
     Val int
     Left *TreeNode
     Right *TreeNode
 }

func InitNode(val int, left *TreeNode, right *TreeNode) (ret *TreeNode){
    ret = new(TreeNode)
    ret.Val = val
    ret.Left = left
    ret.Right = right

    return ret
}

func TreePrint(t1 *TreeNode) {

    if nil == t1 {
        fmt.Printf("null, ")
        return
    } else {
        fmt.Printf("%+v, ", t1.Val)
    }

    TreePrint(t1.Left)
    TreePrint(t1.Right)
}


func MergeTrees(t1 *TreeNode, t2 *TreeNode) (t3 *TreeNode) {

    if nil == t1 && nil == t2 {
        return nil
    }
    
    if nil != t1 && nil == t2{
        return t1
    }else if nil == t1 && nil != t2 {
        return t2
    } else {
        t1.Val += t2.Val
        t1.Left = MergeTrees(t1.Left, t2.Left)
        t1.Right = MergeTrees(t1.Right, t2.Right)
    }

    return t1
}

mergeTrees_test.go

package _617_mergeTrees

import (
    "testing"
    "fmt"
)


func treeEqual(t1 *TreeNode, t2 *TreeNode) bool{
    if t1.Val != t2.Val {
        return false
    }

    if nil == t1.Left && nil != t2.Left {
        return false
    }else if nil != t1.Left && nil == t2.Left {
        return false
    } else if nil != t1.Left && nil != t2.Left {
        left := treeEqual(t1.Left, t2.Left)
        if !left {
            return false
        }
    }

    if nil == t1.Right && nil != t2.Right {
        return false
    }else if nil != t1.Right && nil == t2.Right {
        return false
    }else if nil != t1.Right && nil != t2.Right {
        right := treeEqual(t1.Right, t2.Right)
        if !right {
            return false
        }
    }

    return true
}

func Test_mergeTrees(t *testing.T) {
    t1l2 := InitNode(5, nil, nil)
    t1l1 := InitNode(3, t1l2, nil)
    t1r1 := InitNode(2, nil, nil)
    t1 := InitNode(1, t1l1, t1r1)

    t2l2r1 := InitNode(4, nil, nil)
    t2l2r2 := InitNode(7, nil, nil)
    t2l1r1 := InitNode(1, nil, t2l2r1)
    t2l1r2 := InitNode(3, nil, t2l2r2)
    t2 := InitNode(2, t2l1r1, t2l1r2)

    t3l2r1 := InitNode(5, nil, nil)
    t3l2r2 := InitNode(4, nil, nil)
    t3l2r3 := InitNode(7, nil, nil)

    t3l1r1 := InitNode(4, t3l2r1, t3l2r2)
    t3l1r2 := InitNode(5, nil, t3l2r3)
    t3 := InitNode(3, t3l1r1, t3l1r2)

    fmt.Printf("merge t1:")
    TreePrint(t1)
    fmt.Println()

    fmt.Printf("merge t2:")
    TreePrint(t2)
    fmt.Println()

    ret := MergeTrees(t1, t2)

    ok := treeEqual(t3, ret)

    fmt.Printf("merge t3:")
    TreePrint(t1)
    fmt.Println()

    fmt.Printf("t1:%+v, t2:%+v, t3:%+v\n", t1, t2, t3)
    if !ok {
        t.Errorf("fail, ret.Val want %+v, get %+v\n", t3, ret)
    } else {
        t.Logf("pass")
    }



}

C语言版:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* mergeTrees(struct TreeNode* t1, struct TreeNode* t2) {
    if (t1 && t2) {
    struct TreeNode *node = (struct TreeNode *)malloc(sizeof(struct TreeNode));
    node->val = t1->val + t2->val;
    node->left = mergeTrees(t1 ? t1->left : NULL, t2 ? t2->left : NULL);
    node->right = mergeTrees(t1 ? t1->right : NULL, t2 ? t2->right : NULL);
    return node;
    }
    return t1 ? t1 : t2;
}

C++版

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if (t1 && t2) {
            TreeNode *node = new TreeNode(t1->val + t2->val);
            node->left = mergeTrees(t1 ? t1->left : nullptr, t2 ? t2->left : nullptr);
            node->right = mergeTrees(t1 ? t1->right : nullptr, t2 ? t2->right : nullptr);
            return node;
        }
        return t1 ? t1 : t2;
    }
};

Java版:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null) return t2;
        if (t2 == null) return t1;
        int value = (t1 == null ? 0 : t1.val) + (t2 == null ? 0 : t2.val);
        TreeNode node = new TreeNode(value);
        node.left = mergeTrees(t1 == null ? null : t1.left, t2 == null ? null : t2.left);
        node.right = mergeTrees(t1 == null ? null : t1.right, t2 == null ? null : t2.right);
        return node;
    }
}

链接:

  1. http://www.jianshu.com/p/fc41005c1e83
  2. https://leetcode.com/problems/merge-two-binary-trees/description/

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:miltonsun

查看原文:LeetCode 617. Merge Two Binary Trees

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

805 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传