Its a Topic of DataStructure which covers the Transversal
Size: 112.66 KB
Language: en
Added: Oct 25, 2014
Slides: 10 pages
Slide Content
The process of systematically visiting all the nodes in a tree and performing some computation at each node in the tree is called a tree traversal. Tree Traversal (Definition)
Traversal H D B A C E G I K M O N L J F O G E N F B H
Traversals CODE for each Node: Name public void displayTree (Node n){ if( n == null ) return; printf ( n.data ); displayTree ( n.left ); displayTree ( n.right ); } Visit the node Visit the left subtree , if any. Visit the right subtree , if any. Preorder (N-L-R) public void displayTree (Node n){ if( n == null ) return; displayTree ( n.left ); printf ( n.data ); displayTree ( n.right ); } Visit the left subtree , if any. Visit the node Visit the right subtree , if any. Inorder (L-N-R) public void displayTree (Node n){ if( n == null ) return; displayTree ( n.left ); displayTree ( n.right ); printf ( n.data ); } Visit the left subtree , if any. Visit the right subtree , if any. Visit the node Postorder (L-R-N)
Preorder Traversal H D B A C E G I K M O N L J F O N K I J L E C A D H N-L-R
Inorder Traversal H D B A C E G I K M O N L J F L-N-R O N M L K J I H G F E D C B A Note: An inorder traversal of a BST visits the keys sorted in increasing order.
Postorder Traversal H D B A C E G I K M O N L J F L-R-N H L N O M J K I D F G E B C A
The children of any node in a binary tree are ordered into a left child and a right child A node can have a left and a right child, a left child only, a right child only, or no children The tree made up of a left child (of a node x) and all its descendents is called the left subtree of x Right subtrees are defined similarly 7 Binary-Tree Related Definitions 10 1 3 11 9 8 4 6 5 7 12
Observe the output of the inorder traversal of the BST example two slides earlier It is sorted This is no coincidence As a general rule, if you output the keys (data) of the nodes of a BST using inorder traversal, the data comes out sorted in increasing order 10 Application of Traversal Sorting a BST