Level Order Tree Traversal. Level order traversal of a tree is breadth first traversal for the tree. Last_page Program to count leaf nodes in a binary tree. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Load Comments Share this post!
![]()
METHOD 1 (Use function to print a given level) Algorithm: There are basically two functions in this method. One is to print all nodes at a given level (printGivenLevel), and other is to print level order traversal of the tree (printLevelorder). PrintLevelorder makes use of printGivenLevel to print nodes at all levels one by one starting from root. /.Function to print level order traversal of tree./ printLevelorder(tree) for d = 1 to height(tree) printGivenLevel(tree, d); /.Function to print all nodes at a given level./ printGivenLevel(tree, level) if tree is NULL then return; if level is 1, then print(tree-data); else if level greater than 1, then printGivenLevel(tree-left, level-1); printGivenLevel(tree-right, level-1); Implementation. Filternone Output: Level order traversal of binary tree is - 1 2 3 4 5 Time Complexity: O(n^2) in worst case. For a skewed tree, printGivenLevel takes O(n) time where n is the number of nodes in the skewed tree.
So time complexity of printLevelOrder is O(n) + O(n-1) + O(n-2) +. + O(1) which is O(n^2). METHOD 2 (Use Queue) Algorithm: For each node, first the node is visited and then it’s child nodes are put in a FIFO queue.
PrintLevelorder(tree) 1) Create an empty queue q 2) tempnode = root /.start from root./ 3) Loop while tempnode is not NULL a) print tempnode-data. B) Enqueue tempnode’s children (first left then right children) to q c) Dequeue a node from q and assign it’s value to tempnode Implementation: Here is a simple implementation of the above algorithm. Queue is implemented using an array with maximum size of 500. We can implement queue as linked list also.
Comments are closed.
|
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |