280 likes | 376 Views
Breadth-First Binary Tree Traversal Algorithm. Alyce Brady CS 470: Data Structures CS 510: Computer Algorithms. Reminder: Breadth-First Traversal. A. B. C. D. E. F. G. A B C D E F G. breadth-first-traversal put root node onto a queue while the queue is not empty
E N D
Breadth-First Binary Tree Traversal Algorithm Alyce Brady CS 470: Data Structures CS 510: Computer Algorithms
Reminder:Breadth-First Traversal A B C D E F G A B C D E F G
breadth-first-traversal put root node onto a queue while the queue is not empty dequeue the next node visit the node e.g., print value enqueue the left child node enqueue the right child node Pseudo-Code forBreadth-First Traversal
Breadth-First Search Queue: A B C Current: D E F G A B C D E F G
Breadth-First Search Queue: A A B C Current: D E F G
Breadth-First Search Queue: A A B C Current: D E F G A
Breadth-First Search Queue: A B C Current: D E F G A A
Breadth-First Search Queue: B A B C Current: D E F G A A
Breadth-First Search Queue: C B A B C Current: D E F G A A
Breadth-First Search Queue: C B A B C Current: D E F G B A
Breadth-First Search Queue: C A B C Current: D E F G B A B
Breadth-First Search Queue: D C A B C Current: D E F G B A B
Breadth-First Search Queue: E D C A B C Current: D E F G B A B
Breadth-First Search Queue: E D C A B C Current: D E F G C A B
Breadth-First Search Queue: E D A B C Current: D E F G C A B C
Breadth-First Search Queue: F E D A B C Current: D E F G C A B C
Breadth-First Search Queue: G F E D A B C D E F G Current: C A B C
Breadth-First Search Queue: G F E D A B C D E F G Current: D A B C
Breadth-First Search Queue: G F E A B C D E F G Current: D A B C D
Breadth-First Search Queue: G F E A B C D E F G Current: E A B C D
Breadth-First Search Queue: G F A B C D E F G Current: E A B C D E
Breadth-First Search Queue: G F A B C D E F G Current: F A B C D E
Breadth-First Search Queue: G A B C D E F G Current: F A B C D E F
Breadth-First Search Queue: G A B C D E F G Current: G A B C D E F
Breadth-First Search Queue: A B C D E F G Current: G A B C D E F G
Breadth-First Search A B C D E F G A B C D E F G
Time Complexity Consider each node twice O(n) when put on queue when taken from queue Time and Space Complexityfor Breadth-First Search Alg.
Space Complexity Queue to handle unexplored nodes Queue length = width of lowest level (n/2) O(n) Time and Space Complexityfor Breadth-First Search Alg.