LeetCode-617-Combine Binary Tree (Simple)


1. Description

Given two binary trees, imagine that when you overlay one of them on the other, some nodes of the two binary trees will overlap.

You need to merge them into a new binary tree. The rule of merging is that if two nodes overlap, their values ​​are added together as the new value after the node is merged, otherwise the node that is not NULL will be directly used as the node of the new binary tree.

2. Example

Input:
  Tree 1 Tree 2
       1 2
      / \ / \
    3 2 1 3
   / \ \
  5 4 7

Output:
merged tree:
           3
         / \
       4 5
     / \ \
   5 4 7

3. Analysis

The definition of binary tree is carried out recursively, so the operation on it is also carried out recursively.

In the example, after the root node "1" of Tree 1 and the root node "2" of Tree 2 are merged, the root node "3" of the merged tree is obtained, which is the root "1" of Tree 1 plus the root of Tree 2 " 2".

Then process the left subtree of the root node "1" of Tree 1 and the left subtree of the root node "2" of Tree 2;
finally process the right subtree of the root node "1" of Tree 1 and the root node "2" of Tree 2 "The right subtree.

However, it should be noted that if the root node of two subtrees is empty, it returns empty;
if a node of a certain subtree is empty, it returns the corresponding node of the other subtree;
otherwise, you need to change the value of the root node Add, put the result of the addition on a subtree (or create a new tree), recursively perform the same processing on the left and right subtrees.

4. Code

/**
 * 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 && t2 == null)
            return null;
        // 若某棵子树的根节点为空,则返回不为空的根节点
        else if(t1 == null)
            return t2;
        else if(t2 == null)
            return t1;
        // 否则,两棵子树的根节点均不为空,则将值相加,放到 Tree 1 树中
        //递归地对左子树和右子树进行同样的处理
        else
        {
    
    
            t1.val += t2.val;
            t1.left = mergeTrees(t1.left, t2.left);
            t1.right = mergeTrees(t1.right, t2.right);
        }
        return t1;
    }
}

5. Verification

Insert picture description here

6. Source

  1. LeeCode 617. Merge Binary Trees
    Source: LeetCode
    Link: https://leetcode-cn.com/problems/merge-two-binary-trees
    Copyright is owned by LeetCode Network.

Guess you like

Origin blog.csdn.net/PursueLuo/article/details/108746273