617- merge binary tree

617- merge binary tree

Given two binary tree, when you imagine them to one another on the cover, some nodes will overlap two binary tree.

You will need to merge them into a new binary tree. Consolidation of the rule is that if two nodes overlap, their values are added as the new value of the node after the merger, or not a node as a NULL will direct the new binary tree node.

Example 1:

输入: 
    Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
输出: 
合并后的树:
         3
        / \
       4   5
      / \   \ 
     5   4   7

Note: The merger must start from the root two trees.

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/merge-two-binary-trees
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if(t1 == null) {
            return t2;
        } else 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;
    }

Improve:

    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if(t1 == null) {
            return t2;
        } else if(t2 == null) {
            return t1;
        }

        t1.val = t1.val + t2.val;
        t1.left = mergeTrees(t1.left, t2.left);
        t1.right = mergeTrees(t1.right, t2.right);
        return t1;
    }

Guess you like

Origin www.cnblogs.com/angelica-duhurica/p/12238293.html