Java implementation LeetCode 617 merge binary tree (tree walking)

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 a new value after the merger node, or the node is not NULL will direct the new node as a binary tree.

Example 1:

Input:

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

Output:
The combined tree:

     3
    / \
   4   5
  / \   \ 
 5   4   7

Note: The merger must start from the root two 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_1(TreeNode t1, TreeNode t2) {
        if (t1 == null) {
            return t2;
        }
        if (t2 == null) {
            return t1;
        }
        // 先合并根节点
        t1.val += t2.val;
        // 再递归合并左右子树
        t1.left = mergeTrees(t1.left, t2.left);
        t1.right = mergeTrees(t1.right, t2.right);
        return t1;
    }

    /**
     * 不修改原二叉树的解法
     */
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null && t2 == null) {
            return null;
        }
        // 先合并根节点
        TreeNode root = new TreeNode((t1 == null ? 0 : t1.val) + (t2 == null ? 0 : t2.val));
        // 再递归合并左右子树
        root.left = mergeTrees(t1 == null ? null : t1.left, t2 == null ? null : t2.left);
        root.right = mergeTrees(t1 == null ? null : t1.right, t2 == null ? null : t2.right);
        return root;
    }
}
Released 1675 original articles · won praise 20000 + · views 3.18 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/105201153