Trees(Functions/Traversal)

Tree Data Structures
CSC 221
Review Questions
A
A
B
B
C
D
Inorder traversal? (LVR)
D
C
E
DCBA
DBEAC
Review Questions
A
A
B
B
C
D
Preorder traversal? (VLR)
D
C
E
ABCD
ABDEC
Review Questions
A
A
B
B
C
D
Postorder traversal? (LRV)
D
C
E
DCBA
DEBCA
Level-Order Traversal
Rules:
– Instead of going down to children first, go
across to siblings
– Visits all nodes on a given level in left-to-right
order
1234567
1
3
2
4
5
6
7
Level Order Traversal
• Level order traversal also known as
breadth-first traversal
– Previous traversals were depth first.
• Previous traversals made use of stack
– Figuratively with recursive traversal
• To handle breadth-first search
– need a queue in place of a stack
Level Order Traversal
• Add root node to queue
• For a given node from the queue
– Visit node
– Add nodes left child to queue
– Add nodes right child to queue
Level Order Traversal
void BinaryTree::LevelOrder()
{
Queue<BinaryTreeNode*> queue;
BinaryTreeNode* currentNode = root;
while (currentNode)
{
cout << currentNode->data;
if (currentNode->leftChild) queue.Add(currentNode>leftChild);
if (currentNode->rightChild) queue.Add(currentNode>rightChild;
currentNode = *(queue.Delete(currentNode));
}
}
LevelOrder
Validation
+
*
D
*
/
A
E
C
B
Queue: * E
Output: +
E*D
*
E *
*D
D /C
Level Order Traversal
• Doesn’t have as useful a meaning in
expressions as inorder / preorder /
postorder
• There are problems where useful
– Check heuristic on all paths leading out
– Take hypothesized ‘shortest/best’ path
• Chess – all possible one-step next moves, scoring
mechanism to end-game?
Binary Tree Operations
• Copy constructor:
– Goal: Create a tree that mirrors the current
tree
– Do a tree traversal, creating new nodes in
new tree as encounter first time in current
tree.
Binary Tree Copy Constructor
BinaryTree::BinaryTree(const BinaryTree & input)
{ root = copy(input.root); }
BinaryTreeNode* copy(BinaryTreeNode* current)
{
if (current)
{
BinaryTreeNode *temp = new BinaryTreeNode;
temp->data = current->data;
temp->leftChild = copy(current->leftChild);
temp->rightChild = copy(current->rightChild);
return temp;
}
else return 0;
}
Binary Tree Equivalence
• Operator==:
– Goal: Determine whether or not the two trees
have the same data values and link orderings
– Do a tree traversal,
• Check whether or not nodes in the same place
• Compare data values
Binary Tree Equivalence
bool operator==(const BinaryTree & tree1, const BinaryTree &
tree2)
{ return equal(tree1.root, tree2.root); }
bool equal(BinaryTreeNode* a, BinaryTreeNode* b)
{
if ((!a) && (!b)) return 1; // both null pointers
if (a && b && (a->data == b->data) // same data
&& equal(a->leftChild,b->leftChild) // same left
&& equal(a->rightChild, b->rightChild) // same right
return 1;
return 0;
}