Is this code right for Euler tour in binary trees?

2.6k views Asked by At

I wanted to wite a code which shows EulerTour in a binary tree. I have written code below:

public void EulerTour(Node parent , Node focusNode)
{
    if(focusNode.left!= null)
         EulerTour(parent, focusNode.left);
    if(focusNode.right!= null)
         EulerTour(parent, focusNode.right);
    System.out.println(focusNode);

}

but I have 3 Questions :

  1. Is it right for Euler Tour??

  2. If yes, It seems to be very similar to postOrder Traverse of tree. right?

  3. If it is similar to post Order traverse so what are the differences that we use 2 seperated code?

Thanks in advance

2

There are 2 answers

0
zangw On BEST ANSWER

Here are C++ codes

void Euler_tour(TreeNode* root, vector<int>& result){
    if (root == NULL)
        return;

    result.push_back(root->data);
    if (root->left){
        Euler_tour(root->left, result);
        result.push_back(root->data);
    }
    if (root->right){
        Euler_tour(root->right, result);
        result.push_back(root->data);
    }
}
0
markovuksanovic On
  1. I don't think so.
  2. Very similar but not the same.
  3. Post order traversal is as follows
  1. Visit left child
  2. Visit right child
  3. Visit current node

Euler walk is as follows:

  1. Visit current node
  2. Visit subtree rooted at left child
  3. Visit current node (again)
  4. Visit subtree rooted at right child
  5. Visit current node (again)

Not that in Eulers walk every node will be visited three times. You can find more information about Eulers walk here.