Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
FUNDAMENTALS: DATA STRUCTURES & ALGORITHMS
TRAVERSING THE ADT – BINARY TREE
USING A STACK
Example – Pre-Order Traversal
Let S be an empty instance of the ADT Stack. Let currentNode be set to root
of the Binary Tree.
REPEAT
WHILE ( currentNode Null )
{ Process currentNode // e.g. compare keytype values
PUSH rightsubTree of currentNode onto S
Set currentNode to leftsubTree
}
IF (S is not empty)
POP stack S to currentNode
UNTIL (S is empty)
________________________________
USING A RECURSIVELY DEFINED TRAVERSAL
Example In-order Traversal
private void inorder (BinaryTree tree)
{ if (tree is not empty)
{ inorder ( tree.leftsubTreeReference( ) );
process ( tree );
inorder ( tree.rightsubTreeReference( ) );
}
}
Note:
leftsubTreeReference and rightsubTreeReference are private methods that
return an object reference to the left and right subtrees respectively.
FUNDAMENTALS: DATA STRUCTURES & ALGORITHMS
IMPROVING TRAVERSALS OF BINARY TREES
Every binary tree of n nodes has n+1 unused tree node object references. These can
be used to improve the traversals of binary trees.
Circularly Linked Trees
Several possibilities but unused tree node references used to circularly link back
to head of linear chain of nodes.
Threaded Trees
Example: Threaded Binary Tree for Inorder Traversal
+ A +
+ normal reference
- threaded reference
Start
+ B -
- D-
+ C+
- E +
Finish
+ F +
-G -
-H -
- J -
currentNode
root;
WHILE (inorder traversal is not complete)
{ // traverse down left subtree until an empty subtree is found
WHILE (currentNode.lefttag( ) indicates a leftsubtree)
{ currentNode
root of leftsubtree}
process currentNode; //reached a node with no left subtree
WHILE (currentNode.righttag( ) indicates an empty rightsubtree)
{ currentNode
successor node for traversal;
process currentNode
}
// reached a node that has a right subtree
currentNode
root of rightsubtree;
}