FRTKL

617. Merge Two Binary Trees (Easy)

Problem

https://leetcode.com/problems/merge-two-binary-trees/

  • 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.

Example:

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.

Solution

Go

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode {
    if t1 == nil {
		return t2;
	}
    
	if t2 == nil {
		return t1;
	}
    
	t1.Val += t2.Val;
	t1.Left = mergeTrees(t1.Left, t2.Left);
	t1.Right = mergeTrees(t1.Right, t2.Right);
    
	return t1;
}

PHP

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */
class Solution {

    /**
     * @param TreeNode $t1
     * @param TreeNode $t2
     * @return TreeNode
     */
    function mergeTrees($t1, $t2) {
        if (is_null($t1)) {
            return $t2;
        } elseif (is_null($t2)) {
            return $t1;
        }
        
        $t1->val += $t2->val;
        $t1->left = $this->mergeTrees($t1->left, $t2->left);
        $t1->right = $this->mergeTrees($t1->right, $t2->right);
        
        return $t1;
    }
}

Impression

  • 前回の問題で探索をある程度理解したのでそこまで難しくなかった
    • けどやっぱり再帰をパッとかけるわけではない...
  • 今回は深さ優先探索で再帰的にノードの値を足していけばOK!
Written By Fukuaki TAKANO
fortkle icon

Engineering Manager at Connehito inc.
Please contact me via twitter. @fortkle