VOOZH about

URL: https://www.geeksforgeeks.org/dsa/euler-tour-tree/

⇱ Euler Tour of Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Euler Tour of Tree

Last Updated : 12 Jan, 2023

A Tree is a generalization of connected graph where it has N nodes that will have exactly N-1 edges, i.e one edge between every pair of vertices. Find the Euler tour of tree represented by adjacency list.

Examples:

Input : 
 

👁 Image


Output : 1 2 3 2 4 2 1

Input : 
 

👁 Image


Output : 1 5 4 2 4 3 4 5 1

Euler tour is defined as a way of traversing tree such that each vertex is added to the tour when we visit it (either moving down from parent vertex or returning from child vertex). We start from root and reach back to root after visiting all vertices.
It requires exactly 2*N-1 vertices to store Euler tour.

Approach: We will run DFS(Depth first search) algorithm on Tree as: 
 

👁 Image

  1. Visit root node, i.e 1 
    vis[1]=1, Euler[0]=1 
    run dfs() for all unvisited adjacent nodes(2) 
  2. Visit node 2 
    vis[2]=1, Euler[1]=2 
    run dfs() for all unvisited adjacent nodes(3, 4) 
  3. Visit node 3 
    vis[3]=1, Euler[2]=3 
    All adjacent nodes are already visited, return to parent node 
    and add parent to Euler tour Euler[3]=2 
  4. Visit node 4 
    vis[4]=1, Euler[4]=4 
    All adjacent nodes are already visited, return to parent node 
    and add parent to Euler tour, Euler[5]=2 
  5. Visit node 2 
    All adjacent nodes are already visited, return to parent node 
    and add parent to Euler tour, Euler[6]=1 
  6. Visit node 1 
    All adjacent nodes are already visited, and node 1 is root node 
    so, we stop our recursion here. 

Similarly, for example 2: 
 

👁 Image

Implementation:


Output
1 2 3 2 4 2 1 

Complexity Analysis:

  • Auxiliary Space: O(N) 
  • Time Complexity: O(N)
Comment
Article Tags:
Article Tags: