Java---Merge Binary Trees

Source: Internet
Author: User

Given binary trees and imagine that's when you put one of the them to cover the other, some nodes of the and trees is Overl Apped while the others is not.

You need to the merge them into a new binary tree. The merge rule is so if the nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the not NULL node would be used as the node of the 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.

/** * 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 res=new TreeNode (t1.val+t2.val);        Res.left=mergetrees (t1.left,t2.left);        Res.right=mergetrees (t1.right,t2.right);        return res;        /*                */    }}

Java---Merge Binary Trees

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.