Docsity

Binary Tree Traversal Methods - Algorithms and Applications in Java - Lecture Slides, Slides of Computer Science

Partial preview of the text

Download Binary Tree Traversal Methods - Algorithms and Applications in Java - Lecture Slides and more Slides Computer Science in PDF only on Docsity!

Binary Tree Traversal Methods

  • In a traversal of a binary tree, each element of the binary tree is visited exactly once.
  • During the visit of an element, all action (make a clone, display, evaluate the operator, etc.) with respect to this element is taken.

Binary Tree Traversal Methods

  • Preorder
  • Inorder
  • Postorder
  • Level order

Preorder Example (visit = print)

a

b c

a b c

Preorder Example (visit = print)

a

b c

d e^

f

g (^) h i j

a b d g h e i c f j

Inorder Traversal

public static void inOrder(BinaryTreeNode t)

{

if (t != null) { inOrder(t.leftChild); visit(t); inOrder(t.rightChild); }

}

Inorder Example (visit = print)

a

b c

b a c

Inorder By Projection (Squishing)

a

b c

d e^

f

g (^) h i j

g d h b e i a (^) f j c

Inorder Of Expression Tree

a (^) b

c (^) d

e (^) f

Gives infix form of expression (sans parentheses)!

a + b * c - d / e + f

Postorder Example (visit = print)

a

b c

b c a

Postorder Example (visit = print)

a

b c

d e^

f

g (^) h i j

g h d i e b j f c a

Traversal Applications

a

b c

d e^

f

g (^) h i j

  • Make a clone.
  • Determine height.
  • Determine number of nodes.

Level Order

Let t be the tree root.

while (t != null)

{

visit t and put its children on a FIFO queue; remove a node from the FIFO queue and call it t; // remove returns null when queue is empty

}

Binary Tree Construction

  • Suppose that the elements in a binary tree are distinct.
  • Can you construct the binary tree from which a given traversal sequence came?
  • When a traversal sequence has more than one element, the binary tree is not uniquely defined.
  • Therefore, the tree from which the sequence was obtained cannot be reconstructed uniquely.

Some Examples

preorder = ab

a b

a b

inorder = ab

b a

a b

postorder = ab

b a

b a

level order = ab

a b

a b