Skip to main content

Euler tour of binary tree in c++

C++ program for Euler tour of binary tree. Here more information.

// Include header file
#include <iostream>
using namespace std;
/*
  C++ program for
  Euler tour of a binary tree
*/
// Binary Tree Node
class TreeNode
{
	public: 
    int data;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int data)
	{
		// Set node value
		this->data = data;
		this->left = nullptr;
		this->right = nullptr;
	}
};
class BinaryTree
{
	public: 
    TreeNode *root;
	BinaryTree()
	{
		this->root = nullptr;
	}
	// Recursively Printing the elements of euler path
	void eulerPath(TreeNode *node, TreeNode *parent)
	{
		if (node == nullptr)
		{
			// When tree node empty
			return;
		}
		// Display node value
		cout << "  " << node->data;
		// Recursively visit the left and right subtree
		this->eulerPath(node->left, node);
		this->eulerPath(node->right, node);
		if (parent != nullptr)
		{
			// When parent not null
			cout << "   " << parent->data;
		}
	}
};
int main()
{
	// Create new tree
	BinaryTree *tree = new BinaryTree();
	/*
	        9
	       / \
	      5   7
	     / \   \
	    1   6   11
	   /   / \   \
	  10  4   8   20
	         / \
	        2   3
	  -----------------------
	    Binary Tree
	*/
	tree->root = new TreeNode(9);
	tree->root->left = new TreeNode(5);
	tree->root->right = new TreeNode(7);
	tree->root->left->left = new TreeNode(1);
	tree->root->left->left->left = new TreeNode(10);
	tree->root->left->right = new TreeNode(6);
	tree->root->left->right->left = new TreeNode(4);
	tree->root->left->right->right = new TreeNode(8);
	tree->root->left->right->right->left = new TreeNode(2);
	tree->root->left->right->right->right = new TreeNode(3);
	tree->root->right->right = new TreeNode(11);
	tree->root->right->right->right = new TreeNode(20);
	tree->eulerPath(tree->root, nullptr);
	return 0;
}

Output

  9  5  1  10   1   5  6  4   6  8  2   8  3   8   6   5   9  7  11  20   11   7   9




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment