Equivalent Binary Trees

Question

Two binary trees are equivalent if the sequences from their in order traversals are the same.

Example

I: 
   tree_a               tree_b
           3                      8
         /   \                  /   \ 
        1     8                3    13  
       / \   / \             /   \
      1   2 5   13          1     5 
                          /   \ 
                         1     2  

O: treu because same sequence 1,1,2,3,5,8,13 

Approach

An easy approach is to construct with time and space O(V1)+O(V2)O(V_1) + O(V_2). Just in order traverse tree A and store that and traverse tree B then store that and compare in the end.

A better way is to use two iterators to terminate early and only use the O(h1)+O(h2)O(h_1) + O(h_2)space.

Parallel Approach

We can compute the next value in the iterator in parallel after retrieving it. That will be a lot faster if the tree depth is high.

Goroutine is a more powerful version of coroutine because it can be parallelized.

References

Last updated