Tree traversals
- Tree Traversal: a process to visit all nodes in a tree is called a tree traversal. Typically used to find a key or process all or some keys.
- Traversal always starts at the root of the tree.
Binary Tree Traversal involves three "visits":
- The node is visited(the root)
- The node's left child is traversed
- The node's right child is traversed
Binary Tree Traversals
- The sequence in which those three "visits" are executed determins what kind of traversal it si.
- Typical traversals:
- Pre-order Traversal(Node, Left Child, Right Child)
- In-order Traversal(Left Child, Node, Right Child)
- Post-order Traversal(Left Child, Right Child, Node)
Pre-order(Node, Left, Right)
- Pre-order Traversal(Node, Left Child, Right Child)
- See parent first, then look at left and right branches
In-order(Left Child,Node, Right Child)
- In-order(Left Child,Node, Right Child)
- See left branch first, then look at the parent, and finally look at the right branch
Post-order Traversal(Left Child, Right Child, Node)
- Post-order Traversal(Left Child, Right Child, Node)
- Look at left and right branches first, and then see parent
Level-order(Level-first|Left-Right)
Binary Tree: Recursive Structure
Traversals: Algorithms
- Pre-order Traversal(recursive)
void preOrder(Node node){
if(node != null){
System.out.print(node.getKey());
preOrder(node.getLeftChild);
preOrder(node.getRightChild);
}else{
return;
}
}
- In-order Traversal(recursive)
void inOrder(Node node){
if(node != null){
inOrder(node.getLeftChild);
System.out.print(node.getKey());
inOrder(node.getRightChild);
}else{
return;
}
}
- Post-order Traversal(recursive)
void postOrder(Node node){
if(node != null){
postOrder(node.getLeftChild);
postOrder(node.getRightChild);
System.out.print(node.getKey());
}
}
- Level-order Traversal
void levelOrder(Node node){
if(node !=null){
queue.add(node);
while(queue.isEmpty()==null)
current = queue.dequeue();
System.out.println(current);
queue.enqueue(current children)
}
}
Traversals: Selected Applications
Depth first search(DFS)
-
Pre-order Traversal
- binary tree duplicaiton
-
In-order Traversal
- binary search tree in order processing("show sorted")
-
Post-order Traversal Traversal
- deleting sub-trees
-
Level-order(Level-by-level | left-to-right)
- Breadth first search(BFS)
- finding shortest paths
- calculating maximum flow algorithms