Recursive Binary Tree Traversal - PowerPoint PPT Presentation

1 / 4
About This Presentation
Title:

Recursive Binary Tree Traversal

Description:

In each of these, the left and right subtrees are visited recursively and the ... Tree1.root.level = 1; Tree1.root.getLevel(Tree1.root); Void getLevel(TreeNode Parent) ... – PowerPoint PPT presentation

Number of Views:75
Avg rating:3.0/5.0
Slides: 5
Provided by: yunga
Category:

less

Transcript and Presenter's Notes

Title: Recursive Binary Tree Traversal


1
Recursive Binary Tree Traversal
  • Three classic ways of recursively traversing a
    tree or of visiting every one of its nodes once.
  • In each of these, the left and right subtrees are
    visited recursively and the distinguishing
    feature is when the element in the root is
    visited or processed.
  • In a preorder traversal, the root is visited
    first (pre) and then the left and right subtrees
    are traversed.
  • In an inorder traversal, the left subtree is
    traversed and then the root is visited and
    finally the right subtree is traversed.
  • In a postorder traversal, the left and right
    subtrees are traversed and then the root is
    visited afterwards.
  • void preOrder(Tree T) void inOrder(Tree T)
    void postOrder(Tree T)
  • if( T ! NULL ) if( T ! NULL )
    if( T ! NULL )
  • process(T-gtelt) inOrder( T-gtleft)
    postOrder( T-gtleft)
  • preOrder( T-gtleft) process(T-gtelt)
    postOrder( T-gtright)
  • preOrder( T-gtright) inOrder( T-gtright)
    process(T-gtelt)

2
Recursive Tree Traversal
  • Demo

PreOrder ABDHIEJKCFLMGNO InOrder HDIBJEKALFMCNG
O PostOrder HIDJKEBLMFNOGCA
3
Breadth-first traversal
  • Print tree node level by level

A
\ B
C
\ D
Enqueue the root node While the queue is not
empty Dequeue the head of the queue
if (level(previousNode) lt level(dequeuedNod
print newlin print
dequeued node Enqueue all of the children
of the dequeued node, when the dequeued
node has children.
E
F
G
4
getLevel Method
  • When you call getLevel
  • Tree1.root.level 1
  • Tree1.root.getLevel(Tree1.root)
  • Void getLevel(TreeNode Parent)
  • if(this ! Parent)
  • this.level Parent.level
  • Parent this
  • if(left ! null) left.getLevel(Parent)
  • if(right ! null) right.getLevel(Parent)
Write a Comment
User Comments (0)
About PowerShow.com