1126. 合并两棵二叉树

描述

给出两个二叉树,并想象当你把其中一个覆盖另一个时,两棵树的一些节点重叠,而其他节点则不重叠。

您需要将它们合并到一个新的二叉树中。 合并规则是,如果两个节点重叠,则将节点值加起来作为合并节点的新值。 否则,非空节点将用作新树的节点。

合并过程必须从两个树的根节点开始。

您在真实的面试中是否遇到过这个题?

样例

输入: 
    树 1                     树 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
输出: 
合并的树:
         3
        / \
       4   5
      / \   \ 
     5   4   7
     
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.
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param t1: the root of the first tree
     * @param t2: the root of the second tree
     * @return: the new binary tree after merge
     */
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        // Write your code here
        
        if(t1 == null && t2 == null){
            return null;
        }
        
        TreeNode newTree = new TreeNode((t1==null ? 0 : t1.val) + (t2 == null ? 0 : t2.val));
        newTree.left = mergeTrees((t1 !=null ? t1.left:null),(t2 != null ? t2.left : null));
        newTree.right = mergeTrees((t1 !=null ? t1.right:null),(t2 != null ? t2.right : null));
        
        return newTree;
    }
}

猜你喜欢

转载自www.cnblogs.com/browselife/p/10645623.html