I have the following text from an academic course I took a while ago about in-order traversal (they also call it pancaking) of a binary tree (not BST):
In-order tree traversal
Draw a line around the outside of the tree. Start to the left of the root, and go around the outside of the tree, to end up to the right of the root. Stay as close to the tree as possible, but do not cross the tree. (Think of the tree — its branches and nodes — as a solid barrier.) The order of the nodes is the order in which this line passes underneath them. If you are unsure as to when you go “underneath” a node, remember that a node “to the left” always comes first.
Here's the example used (slightly different tree from below)
However when I do a search on google, I get a conflicting definition. For example the wikipedia example:
Inorder traversal sequence: A, B, C, D, E, F, G, H, I (leftchild,rootnode,right node)
But according to (my understanding of) definition #1, this should be
A, B, D, C, E, F, G, I, H
Can anyone clarify which definition is correct? They might be both describing different traversal methods, but happen to be using the same name. I'm having trouble believing the peer-reviewed academic text is wrong, but can't be certain.
package datastructure;
public class BinaryTreeTraversal {
}
package datastructure;
public class Node {
}
preOrderTraversal >> 4 2 1 3 6 5 7 inOrderTraversal >> 1 2 3 4 5 6 7 postOrderTraversal >> 1 3 2 5 7 6 4
I personally found this lecture quite helpful.
For an inline tree traversal you have to keep in mind that the order of traversal is left-node-right. For the above diagram that you are conflicted on, your error occurs when you read a parent node before reading any leaf(children) nodes to the left.
The proper traversal would be: as far left as possible with leaf nodes(A), return to parent node(B), move to the right, but since D has a child to its left you move down again(C), back up to C's parent(D), to D's right child(E), reverse back to the root(F), move to the right leaf(G), move to G's leaf but since it has a left leaf node move there(H), return to parent(I).
the above traversal reads the node when I have it listed in parenthesis.
this may be late but it could be useful for anyone later .. u just need not to ignore the dummy or null nodes e.g the Node G has a left null node .. considering this null node will make every thing alright ..
If you read carefully you see that the first "definition" says to start left of the root and that the order of the nodes is determined by when you pass under them. So
B
is not the first node, as you pass it from the left on the way toA
, then first pass underA
after which you go up and pass underB
. Therefore it seems that both definitions give the same result.Forget the definitions, it's so much easier to just apply the algorithm:
It's just three lines. Rearrange the order for pre- and post- order.