Similar Inorder Traversal
InterviewTime limit1sMemory limit1024 MB
Simulate a depth-first walk from the root that mimics inorder traversal, and count the total number of moves between nodes.
- Level
Medium4 of 10
- Topics
- Tree, DFS, Simulation, Implementation
- Solved
- No attempts yet
Problem
There is a binary tree with nodes. We want to traverse the tree in a way similar to inorder traversal. Call this a similar inorder traversal.
The traversal starts at the root of the tree and ends at the node that would be visited last in an inorder traversal. The root node is always node 1.
A similar inorder traversal starts at the root node and proceeds as follows.
- If the current node has a left child that has not been visited yet, move to the left child.
- Otherwise, if the current node has a right child that has not been visited yet, move to the right child.
- Otherwise, if the current node is the end of the similar inorder traversal, terminate the similar inorder traversal.
- Otherwise, if the current node has a parent, move to the parent.
- Repeat steps 1 to 4 until the similar inorder traversal terminates.

An inorder traversal of the tree in the figure visits the nodes in the order .
Therefore, the end of the similar inorder traversal is node 7.

As shown in the figure, the similar inorder traversal starts at the root node , ends at node , and proceeds in the order . While performing the similar inorder traversal, it made 10 moves in total.
Here, a move means going from one node to another node once. For example, going from node 1 to node 2 is one move.
We want to find the number of moves made during a similar inorder traversal.
Input
The first line gives the number of nodes in the tree, .
Lines 2 to each give the current node , its left child , and its right child , separated by spaces. A child number of -1 means there is no such child.
Output
Print the total number of moves made during the similar inorder traversal.