Leetcode-617 Merge Two Binary Trees

Description

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.

分析

合并两棵二叉树,如果节点有交集则两个节点的和作为新节点,否则非空节点作为新节点。

从两棵树的 root 节点开始合并,假设合并到了某个节点 t,则考虑如下情况:

  1. 如果 t1 和 t2 都不为 null,那么

    1
    2
    3
    4
    t.val = t1.val + t2.val;
    t.left = 递归(t1.left, t2.left);
    t.right = 递归(t1.right, t2.right);
    return t;
  1. 如果 t1 为 null,那么返回 t2

  2. 如果 t2 为 null,那么返回 t1

Solution

根据分析,写出代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null) return t2;
if (t2 == null) return t1;

TreeNode t = new TreeNode(t1.val+t2.val);
t.left = mergeTrees(t1.left, t2.left);
t.right = mergeTrees(t1.right, t2.right);

return t;
}
}

一遍过,bugfree~~

本文标题:Leetcode-617 Merge Two Binary Trees

文章作者:Pylon, Syncher

发布时间:2019年07月22日 - 08:07

最后更新:2023年03月11日 - 17:03

原始链接:https://0x400.com/fundamental/algorithm/lc-617-merge-tow-binary-trees/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。