The Wayback Machine - https://web.archive.org/web/20241127002943/https://www.geeksforgeeks.org/euler-tour-tree/
Open In App

Euler Tour of Tree

Last Updated : 12 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 : 
 

Output : 1 2 3 2 4 2 1

Input : 
 

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: 
 

  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: 
 

Implementation:

C++




// C++ program to print Euler tour of a
// tree.
#include <bits/stdc++.h>
using namespace std;
 
#define MAX 1001
 
// Adjacency list representation of tree
vector<int> adj[MAX];
 
// Visited array to keep track visited
// nodes on tour
int vis[MAX];
 
// Array to store Euler Tour
int Euler[2 * MAX];
 
// Function to add edges to tree
void add_edge(int u, int v)
{
    adj[u].push_back(v);
    adj[v].push_back(u);
}
 
// Function to store Euler Tour of tree
void eulerTree(int u, int &index;)
{
    vis[u] = 1;
    Euler[index++] = u;
    for (auto it : adj[u]) {
        if (!vis[it]) {
            eulerTree(it, index);
            Euler[index++] = u;
        }
    }
}
 
// Function to print Euler Tour of tree
void printEulerTour(int root, int N)
{
    int index = 0; 
    eulerTree(root, index);
    for (int i = 0; i < (2*N-1); i++)
        cout << Euler[i] << " ";
}
 
// Driver code
int main()
{
    int N = 4;
 
    add_edge(1, 2);
    add_edge(2, 3);
    add_edge(2, 4);
 
    // Consider 1 as root and print
    // Euler tour
    printEulerTour(1, N);
 
    return 0;
}


Java




// Java program to print Euler tour of a
// tree.
import java.util.*;
 
class GFG{
 
static final int MAX = 1001;
static int index = 0;
 
// Adjacency list representation of tree
static ArrayList<
       ArrayList<Integer>> adj = new ArrayList<>();
 
// Visited array to keep track visited
// nodes on tour
static int vis[] = new int[MAX];
 
// Array to store Euler Tour
static int Euler[] = new int[2 * MAX];
 
// Function to add edges to tree
static void add_edge(int u, int v)
{
    adj.get(u).add(v);
    adj.get(v).add(u);
}
 
// Function to store Euler Tour of tree
static void eulerTree(int u)
{
    vis[u] = 1;
    Euler[index++] = u;
     
    for(int it : adj.get(u))
    {
        if (vis[it] == 0)
        {
            eulerTree(it);
            Euler[index++] = u;
        }
    }
}
 
// Function to print Euler Tour of tree
static void printEulerTour(int root, int N)
{
    eulerTree(root);
    for(int i = 0; i < (2 * N - 1); i++)
        System.out.print(Euler[i] + " ");
}
 
// Driver code
public static void main(String[] args)
{
    int N = 4;
     
    for(int i = 0; i <= N; i++)
        adj.add(new ArrayList<>());
         
    add_edge(1, 2);
    add_edge(2, 3);
    add_edge(2, 4);
 
    // Consider 1 as root and print
    // Euler tour
    printEulerTour(1, N);
}
}
 
// This code is contributed by jrishabh99


Python3




# Python program to print Euler tour of a tree.
from collections import defaultdict
 
# Adjacency list representation of tree
adj = defaultdict(list)
 
# Visited dictionary to keep track of visited nodes on our tour
vis = defaultdict(bool)
 
# defaultdict to store Euler Tour
MAX = 1001
Euler = [0]*(2*MAX)
 
# Function to add edges to tree
def add_edge(u, v):
  adj[u].append(v)
  adj[v].append(u)
   
# Function to store Euler Tour of Tree
def eulerTree(u, index):
  vis[u] = True
  Euler[index] = u
  index += 1
  for nbr in adj[u]:
    if not vis[nbr]:
      index = eulerTree(nbr, index)
      Euler[index] = u
      index += 1
  return index
       
# Function to print Euler Tour of Tree
def printEulerTour(root, N):
  index = 0
  eulerTree(root, index)
  for i in range(2*N-1):
    print(Euler[i], end=" ")
     
# Driver Code
N = 4
add_edge(1, 2)
add_edge(2, 3)
add_edge(2, 4)
 
printEulerTour(1, N)


C#




// C# code for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
    const int MAX = 1001;
    static int index = 0;
 
    // Adjacency list representation of tree
    static List<List<int>> adj = new List<List<int>>();
 
    // Visited array to keep track visited
    // nodes on tour
    static int[] vis = new int[MAX];
 
    // Array to store Euler Tour
    static int[] Euler = new int[2 * MAX];
 
    // Function to add edges to tree
    static void add_edge(int u, int v)
    {
        adj[u].Add(v);
        adj[v].Add(u);
    }
 
    // Function to store Euler Tour of tree
    static void eulerTree(int u)
    {
        vis[u] = 1;
        Euler[index++] = u;
 
        foreach (int it in adj[u])
        {
            if (vis[it] == 0)
            {
                eulerTree(it);
                Euler[index++] = u;
            }
        }
    }
 
    // Function to print Euler Tour of tree
    static void printEulerTour(int root, int N)
    {
        eulerTree(root);
        for (int i = 0; i < (2 * N - 1); i++)
            Console.Write(Euler[i] + " ");
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int N = 4;
 
        for (int i = 0; i <= N; i++)
            adj.Add(new List<int>());
 
        add_edge(1, 2);
        add_edge(2, 3);
        add_edge(2, 4);
 
        // Consider 1 as root and print
        // Euler tour
        printEulerTour(1, N);
    }
}
 
// This code is contributed by lokeshpotta20.


Javascript




<script>
 
// Javascript program to print Euler tour of a
// tree.
var MAX = 1001;
 
// Adjacency list representation of tree
var adj = Array.from(Array(MAX), () => Array());
 
// Visited array to keep track visited
// nodes on tour
var vis = Array(MAX);
 
// Array to store Euler Tour
var Euler = Array(2 * MAX);
 
// Function to add edges to tree
function add_edge(u, v)
{
    adj[u].push(v);
    adj[v].push(u);
}
 
// Function to store Euler Tour of tree
function eulerTree(u, index)
{
    vis[u] = 1;
    Euler[index++] = u;
     
    for(var it of adj[u])
    {
        if (!vis[it])
        {
            index = eulerTree(it, index);
            Euler[index++] = u;
        }
    }
    return index;
}
 
// Function to print Euler Tour of tree
function printEulerTour(root, N)
{
    var index = 0; 
    index = eulerTree(root, index);
    for(var i = 0; i < (2 * N - 1); i++)
        document.write(Euler[i] + " ");
}
 
// Driver code
var N = 4;
add_edge(1, 2);
add_edge(2, 3);
add_edge(2, 4);
 
// Consider 1 as root and print
// Euler tour
printEulerTour(1, N);
 
// This code is contributed by rrrtnx
 
</script>


Output

1 2 3 2 4 2 1 

Complexity Analysis:

  • Auxiliary Space: O(N) 
  • Time Complexity: O(N)


Previous Article
Next Article

Similar Reads

Euler tour of Binary Tree
Given a binary tree where each node can have at most two child nodes, the task is to find the Euler tour of the binary tree. Euler tour is represented by a pointer to the topmost node in the tree. If the tree is empty, then value of root is NULL. Examples: Input : Output: 1 5 4 2 4 3 4 5 1 Approach: First, start with root node 1, Euler[0]=1 Go to l
7 min read
Total nodes traversed in Euler Tour Tree
Euler tour of tree has been already discussed which flattens the hierarchical structure of tree into array which contains exactly 2*N-1 values. In this post, the task is to prove that the degree of Euler Tour Tree is 2 times the number of nodes minus one. Here degree means the total number of nodes get traversed in Euler Tour. Examples: Input: Outp
7 min read
Sudo Placement | Placement Tour
Given an array A of N positive integers and a budget B. Your task is to decide the maximum number of elements to be picked from the array such that the cumulative cost of all picked elements is less than or equal to budget B. Cost of picking the ith element is given by : A[i] + (i * K) where, K is a constant whose value is equal to the number of el
10 min read
Print all Knight's tour possible from a starting point on NxN chessboard
Given a N x N chessboard with a Knight initially standing on the Xth row and Yth column, the task is to print all possible paths such that the knight must visit each square exactly once. Example: Input: N = 5, X = 1, Y = 1Output: 1 6 15 10 21 14 9 20 5 16 19 2 7 22 11 8 13 24 17 4 25 18 3 12 23 1 6 11 18 21 12 17 20 5 10 7 2 15 22 19 16 13 24 9 4 2
15+ min read
Knight's tour for maximum points
Given a starting position in a 2D matrix representing a grid of points, the task is to find the minimum number of steps required for a knight to collect the maximum points, subject to the following conditions: The knight can move only as per the rules of a standard chess knight (i.e. two squares in one direction and one square in a perpendicular di
15+ min read
Warnsdorff's algorithm for Knight’s tour problem
Problem : A knight is placed on the first block of an empty board and, moving according to the rules of chess, must visit each square exactly once. Following is an example path followed by Knight to cover all the cells. The below grid represents a chessboard with 8 x 8 cells. Numbers in cells indicate move number of Knight. We have discussed Backtr
15+ min read
Minimum steps to come back to starting point in a circular tour
Consider circular track with n points marked as 1, 2, ...n. A person is initially placed on point k. The person moves m > 0, slot forward (in circular way) in each step. Find the minimum number of steps required so that the person reaches initial point k. Examples: Input : n = 9, k = 2, m = 6 Output : 3 Explanation : Sequence of moves is 2 =>
7 min read
Find the first circular tour that visits all petrol pumps
Given information about N petrol pumps (say arr[]) that are present in a circular path. The information consists of the distance of the next petrol pump from the current one (in arr[i][1]) and the amount of petrol stored in that petrol pump (in arr[i][0]). Consider a truck with infinite capacity that consumes 1 unit of petrol to travel 1 unit dista
15+ min read
The Knight's tour problem
Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that "works". Problems that are typically solved using the backtracking technique have the following property in common. These problems can only be solved by trying every possible configuration and each configuration is tried only once. A Naive solution fo
15+ min read
Euler Method for solving differential equation
Given a differential equation dy/dx = f(x, y) with initial condition y(x0) = y0. Find its approximate solution using Euler method. Euler Method : In mathematics and computational science, the Euler method (also called forward Euler method) is a first-order numerical procedure for solving ordinary differential equations (ODEs) with a given initial v
6 min read
Euler's Four Square Identity
According to Euler's four square identity, the product of any two numbers a and b can be expressed as a sum of four squares if a and b both can individually be expressed as the sum of four squares.Mathematically, if a = [Tex]c1^2 + c2^2 + c3^2 + c4^2 [/Tex]and b = [Tex]d1^2 + d2^2 + d3^2 + d4^2 [/Tex]Then, a * b = [Tex]e1^2 + e2^2 + e3^2 + e4^2 [/T
15+ min read
Euclid Euler Theorem
According to Euclid Euler Theorem, a perfect number which is even, can be represented in the form [Tex](2^n - 1)*(2^n / 2) )) [/Tex]where n is a prime number and [Tex]2^n - 1 [/Tex]is a Mersenne prime number. It is a product of a power of 2 with a Mersenne prime number. This theorem establishes a connection between a Mersenne prime and an even perf
10 min read
Predictor-Corrector or Modified-Euler method for solving Differential equation
For a given differential equation [Tex]\frac{dy}{dx}=f(x, y) [/Tex]with initial condition [Tex]y(x_0)=y_0 [/Tex]find the approximate solution using Predictor-Corrector method.Predictor-Corrector Method : The predictor-corrector method is also known as Modified-Euler method. In the Euler method, the tangent is drawn at a point and slope is calculate
13 min read
Count integers in a range which are divisible by their euler totient value
Given 2 integers L and R, the task is to find out the number of integers in the range [L, R] such that they are completely divisible by their Euler totient value.Examples: Input: L = 2, R = 3 Output: 1 [Tex] [/Tex](2) = 2 => 2 % [Tex] [/Tex](2) = 0 [Tex] [/Tex](3) = 2 => 3 % [Tex] [/Tex](3) = 1 Hence 2 satisfies the condition.Input: L = 12, R
6 min read
Euler zigzag numbers ( Alternating Permutation )
Euler Zigzag numbers is a sequence of integers which is a number of arrangements of those numbers so that each entry is alternately greater or less than the preceding entry.c1, c2, c3, c4 is Alternating permutation where c1 < c2 c3 < c2 c3 < c4...zigzag numbers are as follows 1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521 ......For a given
7 min read
Check if a number is Euler Pseudoprime
Given an integer N and a base number A, the task is to check whether N is a Euler Pseudoprime to the given base A. An integer N is called Euler Pseudoprime to the base A, if A > 0 and N is an odd composite number.A and N are co-prime i.e. GCD(A, N) = 1.A(N - 1) / 2 % N is either 1 or N - 1. Examples: Input: N = 121, A = 3 Output: YesInput: N = 3
9 min read
Euler's Factorization method
Given a number N, the task is to find the factors of N. Examples: Input: N = 1000009 Output: 293 3413 Explanation: 293 * 3413 = 1000009Input: N = 100000 Output: 800 125 Explanation: 800 * 125 = 100000 Euler's Factorization method: Euler's factorization method works on the principle that all the numbers N which can be written as the sum of two power
15+ min read
Conversion of an Undirected Graph to a Directed Euler Circuit
Given an undirected graph with V nodes (say numbered from 1 to V) and E edges, the task is to check whether the graph is an Euler Graph or not and if so then convert it into a Directed Euler Circuit. A Directed Euler Circuit is a directed graph such that if you start traversing the graph from any node and travel through each edge exactly once you w
10 min read
Count of elements having Euler's Totient value one less than itself
Given an array arr[] of N integers, and a range L to R, the task is to find the total number of elements in the array from index L to R that satisfies the following condition: [Tex]F(arr[i]) = arr[i] - 1 [/Tex] where F(x) is Euler's Totient Function. Examples: Input: arr[] = {2, 4, 5, 8}, L = 1, R = 3 Output: 2 Explanation: Here in the given range,
9 min read
Probability of Euler's Totient Function in a range [L, R] to be divisible by M
Given three integers L, R, and M, the task is to find the probability of Euler's Totient Function of a number in the range [L, R] is divisible by M. Euler’s Totient function is the count of numbers in {1, 2, 3, …, N} that are relatively prime to N, i.e., the numbers whose GCD (Greatest Common Divisor) with N is 1. Examples: Input: L = 1, R = 5, M =
12 min read
Check if Euler Totient Function is same for a given number and twice of that number
Given an integer N, the task is to check whether the Euler’s Totient Function of N and 2 * N are the same or not. If they are found to be the same, then print “Yes”. Otherwise, print “No”. Examples: Input: N = 9 Output: Yes Explanation: Let phi() be the Euler Totient function Since 1, 2, 4, 5, 7, 8 have GCD 1 with 9. Therefore, phi(9) = 6. Since 1,
7 min read
Generate an array having sum of Euler Totient Function of all elements equal to N
Given a positive integer N, the task is to generate an array such that the sum of the Euler Totient Function of each element is equal to N. Examples: Input: N = 6Output: 1 6 2 3 Input: N = 12Output: 1 12 2 6 3 4 Approach: The given problem can be solved based on the divisor sum property of the Euler Totient Function, i.e., The Euler Totient Functio
5 min read
Sum of Euler Totient Functions obtained for each divisor of N
Given a positive integer N, the task is to find the sum of the Euler Totient Function for all the divisor of the given number N. Examples: Input: N = 3Output: 3Explanation:Divisors of 3 are {1, 3}. The Euler totient function for the values 1 and 3 are 1 and 2 respectively.Therefore, the required sum is 1 + 2 = 3. Input: N = 6Output: 6 Naive Approac
3 min read
Euler Circuit in a Directed Graph
Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex. A graph is said to be eulerian if it has a eulerian cycle. We have discussed eulerian circuit for an undirected graph. In this post, the same is discussed for a directed graph. For example, the followi
13 min read
Euler's Totient function for all numbers smaller than or equal to n
Euler's Totient function ?(n) for an input n is the count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. For example, ?(4) = 2, ?(3) = 2 and ?(5) = 4. There are 2 numbers smaller or equal to 4 that are relatively prime to 4, 2 numbers smaller or equal to 3 that are
13 min read
Euler's criterion (Check if square root under modulo p exists)
Given a number 'n' and a prime p, find if square root of n under modulo p exists or not. A number x is square root of n under modulo p if (x*x)%p = n%p. Examples : Input: n = 2, p = 5 Output: false There doesn't exist a number x such that (x*x)%5 is 2 Input: n = 2, p = 7 Output: true There exists a number x such that (x*x)%7 is 2. The number is 3.
11 min read
Project Euler
What is Project Euler? Project Euler is a series of challenging problems that require mathematical and programming skills. Somebody who enjoys learning new area of mathematics, project Euler is going to be a fun journey. Where are the problems ? The problems are right here in their official archive. Let's solve a problem from the archive and unders
3 min read
Minimum edges required to add to make Euler Circuit
Given a undirected graph of n nodes and m edges. The task is to find minimum edges required to make Euler Circuit in the given graph. Examples: Input : n = 3, m = 2 Edges[] = {{1, 2}, {2, 3}} Output : 1By connecting 1 to 3, we can create a Euler Circuit. For a Euler Circuit to exist in the graph we require that every node should have even degree be
11 min read
Optimized Euler Totient Function for Multiple Evaluations
Euler Totient Function (ETF) ?(n) for an input n is count of numbers in {1, 2, 3, …, n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. Examples: ?(5) = 4 gcd(1, 5) is 1, gcd(2, 5) is 1, gcd(3, 5) is 1 and gcd(4, 5) is 1 ?(6) = 2 gcd(1, 6) is 1 and gcd(5, 6) is 1, Recommended PracticeEuler Totient
9 min read
Euler Totient Function in Python
Euler’s Totient function, also known as Euler's Phi Function Φ (n) is a mathematical function that counts the number of positive integers up to a given integer n that are relatively prime to n. i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. Examples : Input: Φ(1) = 1 Output: gcd(1, 1) is 1 Input: Φ(2) = 1Output: gcd(1, 2) is 1,
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg