Traversing Two Trees in Parallel
tags: treetraversal
Given two trees, determine whether they are copies of one another. This is a common coding interview question.
Clarification Questions
It is intentionally vague. Sometimes, interviewers will ask question to see if you can define the problem scope by asking the necessary clarifying questions.
 What are the data structures?
 What’s the function signature?
 Are there classes?
 What does the tree look like, how many children are there?
Variations
It is up to you how you would design it. So, this is about traversing two trees in parallel. There are variations of this question like:
 Are two trees copies of each other?
 Is there a node in one tree that is considered the same as a node in another tree?
Solution
You might be familiar with traversing a single tree. But to traverse two trees at the same time, it tests if you understand the algorithm. There is nothing tricky about this question. We will see the code with two variations.
First, think about how you represent children. Sometimes it is simpler to represent them as an array, rather than as a left
node and a right
node. Sometimes, a tree can have multiple fanouts, so the array representation is more flexible. It depends on the problem.
The second thing is the implementation is in recursive form and then in iterative form. You will find that the recursive form is a bit simpler. The iterative form requires passing a lot of state around, and nearly warrants creating a new data structure just to encapsulate the state of two nodes. I get away with it using a stack of arrays
for brevity.
This solution uses objectoriented style. So instead of having a function isClone(a, b)
, I’m going to use the form a.isClone(b)
. Just be aware that there are multiple ways of doing these method params.


Identifying Problem Isomorphism
“Traversing Two Trees in Parallel” is isomorphic to “Same Tree”.
In “Traversing Two Trees in Parallel”, you have to traverse two trees simultaneously and perform some operation based on the nodes at the corresponding positions in the two trees.
Similarly, the “Same Tree” requires you to traverse two trees simultaneously to check if they are the same. Specifically, you need to check if the two trees have the same structure and the same nodes at the corresponding positions.
In both problems, you need to use a tree traversal technique, such as depthfirst search or breadthfirst search, to traverse the two trees simultaneously and perform an operation based on the nodes at the corresponding positions.
“Same Tree” is simpler because the operation to be performed based on the corresponding nodes is a simple comparison, whereas the “Traversing Two Trees in Parallel” problem could involve a more complex operation, depending on the specific problem requirements.
Given two trees, determine whether they are copies of one another.
Clarification Questions
It is intentionally vague. Sometimes, interviewers will ask question to see if you can define the problem scope by asking the necessary clarifying questions.
 What are the data structures?
 What’s the function signature?
 Are there classes?
 What does the tree look like, how many children are there?
Problem Classification
This problem can be classified as follows:
Data Structures: This problem involves working with tree data structures, specifically binary trees if each node has at most two children.
Comparison: The task involves comparing two trees, which requires understanding of how to traverse and compare the nodes of two trees.
Pattern Recognition: You are determining if two data structures (in this case, trees) are identical or copies of each other.
Graph Theory: Trees are a special type of graph, so this problem could be seen in the context of graph theory.
Recursive Structures: Trees are inherently recursive as each subtree is a tree itself. Thus, the problem involves understanding and working with recursive structures.
The solution will involve algorithms and possibly recursion, depending on how you choose to compare the two trees.
Variations
It is up to you how you would design it. So, this is about traversing two trees in parallel. There are variations of this question like:
 Are two trees copies of each other?
 Is there a node in one tree that is considered the same as a node in another tree?
Solution
You might be familiar with traversing a single tree. But when asked to traverse two trees at the same time, it tests if you understand the algorithm. There is nothing tricky about this questions. We will see the code with two variations.
First, think about how you represent children. Sometimes it is simpler to represent them as an array, rather than as a left
node and a right
node. Sometimes, a tree can have multiple fanouts, so the array representation is more flexible. It depends on the problem at hand.
The second thing is the implementation is in recursive form and then in iterative form. You will find that the recursive form is a bit simpler. The iterative form requires passing a lot of state around, and nearly warrants creating a new data structure just to encapsulate the state of two nodes. I get away with it using a stack of arrays
for brevity.
This solution uses objectoriented style. So instead of having a function isClone(a, b)
, I’m going to use the form a.isClone(b)
. Just be aware that there are multiple ways of doing these method params.


Comparing Tree Structures: A Detailed Walkthrough of Recursive and Iterative Solutions
The problem at hand is to determine if two given trees are identical or not. This is a common question asked in coding interviews to test your understanding of tree traversal algorithms and your ability to compare two tree structures.
Clarifying Questions
The problem statement is left intentionally vague, so your first task is to clarify the problem statement by asking relevant questions. This shows your interviewer that you have a good problemsolving mindset and that you don’t jump into coding without understanding the problem first. Here are a few clarifying questions you might ask:
 What are the data structures? Understanding the structures of the trees is essential. Are we dealing with binary trees, or can a node have more than two children?
 What’s the function signature? In other words, how is the function being called? Is the tree passed as an argument or are we expected to work with a global tree?
 Are there classes? Are the trees constructed using a Tree class or are they built using basic data structures like arrays or linked lists?
 What does the tree look like, how many children are there? Understanding the shape of the tree and the number of children at each node can influence the strategy you choose for traversing and comparing the trees.
Variations
The problem statement can have several variations, such as:
 Are two trees copies of each other? In this variation, you are asked to check if the two trees are identical in their structure and node values.
 Is there a node in one tree that is considered the same as a node in another tree? This variation is slightly different. Here, you’re not asked to compare the entire trees, but rather to find a matching node between two trees.
Solution
The problem involves traversing two trees at the same time and comparing their structures and node values. You can use both recursive and iterative methods to solve this problem.
In the recursive approach, you recursively compare the value of the current node and the number of children, and then recursively call the function on the children of the current nodes.
In the iterative approach, you use a stack to keep track of the nodes to be compared. This solution involves more state management as you have to manually keep track of the nodes to be compared next.
The implementation uses an objectoriented style where the isClone
method belongs to the Node class. The choice between function isClone(a, b)
and a.isClone(b)
depends on your preference and the specific requirements of your coding interview.
The solution you provided is in Python and it demonstrates both recursive and iterative approaches to solving the problem. The solution assumes that the trees are constructed using a Node class, where each node has a value and a list of its children. It checks if the two trees are identical in both structure and node values.
Here, isClone
is the recursive function and isCloneIterative
is the iterative function. Both functions first compare the values of the nodes, then the lengths of the children lists, and finally each child node recursively or iteratively. The example at the end creates two identical trees and tests both functions, which correctly output that the two trees are identical.
The provided solution correctly solves the problem and demonstrates a good understanding of both recursive and iterative tree traversal algorithms.
Language Agnostic Coding Drills
Here’s a potential arrangement of the drills from simplest to most complex:
Conditional Statements Drill: Write a program that can identify whether a number is odd or even.
 This is a simple introduction to conditional statements, and only requires understanding basic arithmetic and control flow.
List (Array) Data Structures Drill: Create a list, add elements, remove elements, sort the list, and find the length of the list.
 This drill involves a bit more complexity as it deals with a data structure (lists/arrays) and various operations on it.
Loops Drill: Create a program that iterates over a list of numbers and prints each one.
 This drill requires understanding of list (or array) data structures and iteration, increasing complexity a bit more.
ObjectOriented Programming (OOP) Drill: Design a basic object model, such as a model for a “Dog” that includes characteristics (name, age, breed) and actions (bark, eat).
 This is a first step into OOP, requiring understanding of classes and objects, as well as encapsulation.
Initialization and methods in OOP Drill: Extend the “Dog” model from the first drill to initialize name, age, and breed at the creation of a new dog object. Create a new method to modify the dog’s name.
 This builds on the previous drill, adding complexity by introducing the constructor and methods.
Recursion Drill: Implement a function to calculate the factorial of a number using recursion.
 Understanding recursion can be challenging for beginners as it requires thinking in terms of dividing a problem into smaller problems. This is a good intermediate level drill.
Tuple Data Structures Drill: Create a tuple, access its elements, and understand the immutability of tuples (they can’t be modified once created).
 While the operations themselves are not more complex than those for a list, the immutable nature of tuples adds an extra layer of understanding.
Tree Data Structures Drill: Construct a simple tree structure and add nodes to it.
 This drill involves more complex data structures and possibly recursive thinking, making it more challenging than the previous ones.
Stack Data Structures Drill: Construct a basic stack structure and perform operations like push, pop, and peek (view the top element).
 Understanding and implementing a stack data structure requires a solid understanding of both data structures and control flow.
Iteration Method Drill: Implement a function to calculate the factorial of a number, but this time using an iterative approach (loops), not recursion.
 Although the problem is the same as in the recursion drill, solving it iteratively requires a different kind of thinking and a better understanding of loops, making this a more advanced exercise.
This sequence allows for gradual building of skills, each new drill introducing new concepts or adding complexity to concepts introduced in previous drills.
The drills are languageagnostic and the concepts apply to most modern programming languages. While certain terms may have slightly different names in different languages (for instance, lists are often called arrays in some languages), the core ideas remain the same:
ObjectOriented Programming (OOP): Nearly all modern languages support OOP to some degree, including Java, C++, Python, JavaScript, Ruby, etc.
Initialization and methods in OOP: These concepts apply to any language that supports objectoriented programming.
Tree Data Structures: Trees are a universal concept in computer science and are not tied to a specific language.
List (Array) Data Structures: Lists, or arrays, are a basic data structure in virtually every language.
Recursion: Recursion is a universal concept and can be implemented in virtually all programming languages.
Conditional Statements: Conditional (ifelse) statements are a fundamental control structure in virtually all languages.
Loops: Looping constructs, such as
for
andwhile
loops, are present in virtually all programming languages.Stack Data Structures: Stacks are another universal data structure that can be implemented in virtually any language.
Iteration Method: Iteration is a fundamental concept in virtually all programming languages.
Tuple Data Structures: While not all languages have a data structure called a “tuple” per se, most have some equivalent. In languages where no such structure exists, a similar effect can often be achieved using other data structures.
It should be noted, however, that the specific syntax and some of the capabilities will vary from language to language. So while these concepts are universally applicable, the way in which they are implemented may not be. Always refer to the documentation of the specific language you are using for precise details.
Python Drills
The provided Python code is implementing a basic Tree structure and providing methods to compare if two trees are the same (clone) using recursive and iterative (using stack) methods.
Here are the concepts involved, along with potential coding drills:
ObjectOriented Programming: Understanding how to create classes and objects in Python, using methods, and understanding self in Python.
 Drill: Create a simple class like a Dog class that has attributes like name, age, and breed and methods like bark and age_increase.
Initialization and methods in classes: Understanding the
__init__
function, how to create methods inside a class. Drill: Add a
__init__
method to the Dog class from drill 1 that sets name, age, and breed, and create a new method to change the dog’s name.
 Drill: Add a
Data Structures  Trees: Understanding of tree data structures, nodes, children.
 Drill: Implement a simple binary tree and add nodes to it.
Data Structures  Lists: Python lists, iterating over lists, list length.
 Drill: Create a list, add elements to it, remove elements, sort the list, and find the length of the list.
Recursion: Understanding of recursion, how to use recursion in Python.
 Drill: Write a recursive function to calculate factorial of a number.
Conditional Statements: Using if conditions in Python.
 Drill: Write a program that prints “even” if a number is even and “odd” otherwise.
Loops: Using for loops and while loops in Python.
 Drill: Write a program that iterates over a list of numbers and prints each one.
Data Structures  Stacks: Understanding of stack data structure, push and pop operations.
 Drill: Implement a simple stack and perform operations like push, pop, and peek.
Iterative method (as opposed to recursion): Understanding how to use loops and conditions to achieve the same result as recursion.
 Drill: Write a function to calculate factorial of a number using a loop instead of recursion.
Tuples: Understanding of Python tuples, creating, and accessing tuples.
 Drill: Create a tuple, access its elements, and try modifying a tuple (which should give an error as tuples are immutable).
These concepts and the corresponding coding drills, if learned and practiced well, will help you understand and implement the given algorithm in a better way.
Solution for Coding Drills in Python
Here are Python code examples for each of the drills related to basic tree structures and comparison of two trees:
 Understanding Basic Data Structures  Trees:


 Building a Tree:


 Creating a Recursive Function to Compare Two Trees:


 Creating an Iterative Function (using stack) to Compare Two Trees:


 Using the Tree Comparison Functions:


The drills start with understanding the basic data structure (trees), then move to building a tree, then creating recursive and iterative functions to compare two trees, and finally using these functions to compare two actual trees.
Learning Objectives
When it comes to traversing two trees in parallel, there are certain specific skills and objectives to target for developers:
Understanding Tree Structures and Tree Traversal: This involves understanding binary trees, the relationship between nodes, and how to traverse them using different algorithms (like DepthFirst Search and BreadthFirst Search).
Simultaneous Tree Traversal: Once individual tree traversal is understood, developers need to learn how to traverse two trees in parallel. This is important in tasks like checking if two trees are identical or merging two trees.
Handling Disparities Between Trees: It is rare for two trees to be identical in structure. Developers need to be able to handle cases where one tree may have more nodes than the other or where the trees differ in depth.
Comparison of Nodes: While traversing two trees in parallel, developers often have to compare the nodes at the same position in both trees. This skill can be crucial in various problems.
Algorithm Design: The ability to design and implement an algorithm that efficiently traverses two trees in parallel is the ultimate objective.
Once these objectives are identified, they must be broken down into specific, attainable targets for the duration of the teaching session. This could involve practicing on different tree structures, incrementally increasing complexity, and integrating this new skill with previously learned concepts such as tree construction or balancing.
Here’s how we can map the learning path for “Traversing Two Trees in Parallel”:
Best Route to Practice Objective: Start with a thorough understanding of tree structures and tree traversal techniques. From there, transition into simultaneous traversal of two trees, comparisons between nodes, and finally, handling disparities.
Drill Design: Create drills that focus on each of these skills individually, gradually integrating them as proficiency improves. For instance, an initial drill might involve simple tree traversal, while a later drill might involve traversing two different trees simultaneously.
Drill Objectives: Ensure that each drill aligns with the overall objectives. The primary goal should always be to increase proficiency in traversing two trees in parallel.
Naming Skills, Drills, and Techniques: Naming these elements creates mental anchors for learners. For example, “Simultaneous BreadthFirst Traversal” could be a name for a drill focusing on traversing two trees at once.
Breaking Down Learning Units: Start with basic tree traversal before moving onto more complex tasks, such as traversing two trees simultaneously or handling disparities between the trees. Each new skill should build on the last, forming a coherent learning pathway.
Matching Skills to Situations: Use a variety of tree configurations to practice these skills. This variety will help learners understand when to use each technique and how to adapt their approach to different situations.
Scope and Sequence Document: Document the order in which these skills should be learned, the drills associated with each skill, and the estimated time required for practice. This document serves as a roadmap for the learning journey, making the process more manageable and less overwhelming.
Remember, the ultimate goal is to build proficiency in traversing two trees in parallel. Each step should contribute to that end goal.
Here are a few concrete drill examples for “Traversing Two Trees in Parallel”:
Single Tree Traversal: Begin with single tree traversal. Learners are given a binary tree and asked to perform both depthfirst (inorder, preorder, and postorder) and breadthfirst traversals.
Basic TwoTree Traversal: Given two identical binary trees, learners are tasked with traversing both trees simultaneously using depthfirst or breadthfirst traversal and printing the nodes. This drill helps learners get comfortable with managing two traversal processes at once.
TwoTree Traversal with Comparison: In this drill, learners are given two different binary trees. They need to traverse both trees simultaneously and check if the corresponding nodes in both trees have the same value. This drill focuses on not just traversal but also on comparison.
TwoTree Traversal with Handling Disparities: Extend the above drill by adding a twist. The given binary trees are of different structures (i.e., have a different number of nodes or levels). The learners need to handle these disparities elegantly while trying to traverse both trees in parallel.
Mixed Drill: This drill involves a series of binary tree pairs, where learners must apply the most suitable traversal technique for each pair. They’ll have to decide which method is best based on the tree’s characteristics. This drill emphasizes applying the right skills to the right situations.
Timed Drills: To push the learners a bit out of their comfort zone, timed drills can be added. Here, learners are given binary tree pairs and asked to perform certain operations (like checking for tree symmetry) within a certain time limit.
Remember, each of these drills should be practiced repeatedly until the learner feels comfortable with the concepts and techniques. The key to mastering such complex skills is consistent practice and iteration.
In the context of ‘Traversing Two Trees in Parallel’, the learning objectives could be as follows:
Understand Tree Data Structures: Learners should be able to understand what trees are, their structure, properties, and common uses in computer science.
Master Single Tree Traversal: Learners should master the techniques of traversing a single tree, including preorder, inorder, postorder, and levelorder traversals.
Comprehend Parallel Tree Traversal: Learners should understand the concept of parallel tree traversal, i.e., visiting nodes of two trees in a synchronized way.
Apply Parallel Tree Traversal: Learners should be able to apply the parallel traversal techniques to solve problems. They should understand how to traverse two trees in parallel in different scenarios and be able to adapt their approach depending on the situation.
Combine Previous Skills: Learners should integrate their previously acquired knowledge of tree data structures and single tree traversal with the new skill of parallel tree traversal.
Problem Solving and Application: By the end of the session, learners should be able to identify when and why parallel tree traversal is beneficial and apply this technique to solve relevant problems.
Analytical Thinking: Learners should enhance their analytical thinking and problemsolving abilities, which are crucial in understanding and implementing complex data structure manipulations like parallel tree traversal.
Each of these objectives should be specifically defined, attainable within the time frame of the training session, and focused on the practical application of the skills learned.