This page is still under construction.

Parts of this page are still being built. What you see may change.

Similar Inorder Traversal

Interview

Time limit1sMemory limit1024 MB

Summary
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 NN 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.

  1. If the current node has a left child that has not been visited yet, move to the left child.
  2. Otherwise, if the current node has a right child that has not been visited yet, move to the right child.
  3. Otherwise, if the current node is the end of the similar inorder traversal, terminate the similar inorder traversal.
  4. Otherwise, if the current node has a parent, move to the parent.
  5. 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 4→2→5→1→6→3→74 \rightarrow 2 \rightarrow 5 \rightarrow 1 \rightarrow 6 \rightarrow 3 \rightarrow 7.

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 11, ends at node 77, and proceeds in the order 1→2→4→2→5→2→1→3→6→3→71 \rightarrow 2 \rightarrow 4 \rightarrow 2 \rightarrow 5 \rightarrow 2 \rightarrow 1 \rightarrow 3 \rightarrow 6 \rightarrow 3 \rightarrow 7. 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, NN.

Lines 2 to N+1N + 1 each give the current node aa, its left child bb, and its right child cc, 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.

Constraints

  • 1≤N≤100,0001 \le N \le 100,000
  • 1≤a,b≤N1 \le a, b \le N

Examples2

  1. Example 1

    Input
    7
    1 2 3
    2 4 5
    3 6 7
    4 -1 -1
    5 -1 -1
    6 -1 -1
    7 -1 -1
    
    Expected output
    10
    
  2. Example 2

    Input
    1
    1 -1 -1
    
    Expected output
    0