📓
Algorithms
  • Introduction to Data Structures & Algorithms with Leetcode
  • Strings
    • Dutch Flags Problem
      • List Partitoning
    • Counters
      • Majority Vote
      • Removing Parentheses
      • Remove Duplicates from Sorted Array
    • Maths
      • Lone Integer
      • Pigeonhole
      • Check If N and Its Double Exist
      • Find Numbers with Even Number of Digits
    • Two Pointers
      • Remove Element
      • Replace Elements with Greatest Element on Right Side
      • Valid Mountain Array
      • Sort Array by Parity
      • Squares of a Sorted Array
      • Max Consecutive Ones
    • Sliding Window
      • Max Consecutive Ones 3
    • Stacks
      • Balanced Brackets
    • General Strings & Arrays
      • Move Zeros
      • Unique Elements
      • Merge Sorted Array
    • Matrices
      • Valid Square
      • Matrix Search Sequel
  • Trees
    • Untitled
  • Recursion
    • Introduction
    • Backtracking
      • Permutations
  • Dynamic Programming
    • Introduction
    • Minimum (Maximum) Path to Reach a Target
      • Min Cost Climbing Stairs
      • Coin Change
      • Minimum Path Sum
      • Triangle
      • Minimum Cost to Move Chips to The Same Position
      • Consecutive Characters
      • Perfect Squares
    • Distinct Ways
      • Climbing Stairs
      • Unique Paths
      • Number of Dice Rolls with Target Sum
    • Merging Intervals
      • Minimum Cost Tree From Leaf Values
    • DP on Strings
      • Levenshtein Distance
      • Longest Common Subsequence
  • Binary Search
    • Introduction
      • First Bad Version
      • Sqrt(x)
      • Search Insert Position
    • Advanced
      • KoKo Eating Banana
      • Capacity to Ship Packages within D Days
      • Minimum Number of Days to Make m Bouquets
      • Split array largest sum
      • Minimum Number of Days to Make m Bouquets
      • Koko Eating Bananas
      • Find K-th Smallest Pair Distance
      • Ugly Number 3
      • Find the Smallest Divisor Given a Threshold
      • Kth smallest number in multiplication table
  • Graphs
    • Binary Trees
      • Merging Binary Trees
      • Binary Tree Preorder Traversal
      • Binary Tree Postorder Traversal
      • Binary Tree Level Order Traversal
      • Binary Tree Inorder Traversal
      • Symmetric Tree
      • Populating Next Right Pointers in Each Node
      • Populating Next Right Pointers in Each Node II
      • 106. Construct Binary Tree from Inorder and Postorder Traversal
      • Serialise and Deserialise a Linked List
      • Maximum Depth of Binary Tree
      • Lowest Common Ancestor of a Binary Tree
    • n-ary Trees
      • Untitled
      • Minimum Height Trees
    • Binary Search Trees
      • Counting Maximal Value Roots in Binary Tree
      • Count BST nodes in a range
      • Invert a Binary Tree
      • Maximum Difference Between Node and Ancestor
      • Binary Tree Tilt
  • Practice
  • Linked Lists
    • What is a Linked List?
    • Add Two Numbers
      • Add Two Numbers 2
    • Reverse a Linked List
    • Tortoise & Hare Algorithm
      • Middle of the Linked List
  • Bitshifting
    • Introduction
  • Not Done Yet
    • Uncompleted
    • Minimum Cost For Tickets
    • Minimum Falling Path Sum
Powered by GitBook
On this page

Was this helpful?

  1. Graphs
  2. Binary Trees

Merging Binary Trees

PreviousBinary TreesNextBinary Tree Preorder Traversal

Last updated 4 years ago

Was this helpful?

Given two binary trees node0 and node1, return a merge of the two trees where each value is equal to the sum of the values of the corresponding nodes of the input trees. If only one input tree has a node in a given position, the corresponding node in the new tree should match that input node.

For example, given

   0         7
  / \       / \
 3   2     5   1
    /
   3

Return

   7
  / \ 
 8   3
    /
   3

Constraints

  • n ≤ 100,000 where n is the number of nodes in node0

  • m ≤ 100,000 where m is the number of nodes in node1

Example 1

Input

node0 = [1, [0, null, null], null]
node1 = [1, null, null]

Output

[2, [0, null, null], null]

We are performing an in-order traversal (note that pre-order and post-order work as well).

We perform this on both trees at the same time, and add the nodes at each level.

By performing it at the same same, we are traversing the trees in the exact same way which means all we need to do is add the values of the nodes.Implementation

Our basecases are when either of the nodes are none. If they are, we return the other node.

This fixes the problem of our tree looking like:

                  10
                  +
                  |
                  |
                  |
                  |
                  |
                  |
                  |
                  |
                  |
       +----------+------------+
       |                       |
       |                       |
       |                       +
      9|                       7
+----------+
|          |
+         ++
12         11

(Not a binary tree, but it still explains the problem).

When we reach 7 on the other side, if we didn't return the left nodes we would exit the program.

This way essentially we are saying "add X and Y together, but if X doesn't exist then 0 + Y = Y, so return Y. Same for if Y doesn't exist, return X".

We need to use a traversal method, any of them work for this problem.

Key Takeaways

  • Traverse both trees at same time

  • Compare node1 and node1 from tree1 and tree2

  • Merge it all into one tree in-place

  • Return the tree. Note: recursion goes from bottom-up, so when we return node0 we return the whole tree.

Time Complexity

O(h + h1) where H is the height of tree 0 and H1 is the height of tree 1.Space Complexity

O(1) space since we do it entirely in-place, no extra data structure is needed.

# class Tree:
#     def __init__(self, val, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def solve(self, node0, node1):
        if not node0:
            return node1
        if not node1:
            return node0

        node0.left = self.solve(node0.left, node1.left)
        node0.val += node1.val
        node0.right = self.solve(node0.right, node1.right)

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