There are two ways to conduct BFS on tree.
Solution 1 -- Given level
Use recursion to find given level, and print.
/*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);
Solution 2 -- Queue
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) temp_node = root /*start from root*/ 3) Loop while temp_node is not NULL a) print temp_node->data. b) Enqueue temp_node’s children (first left then right children) to q c) Dequeue a node from q and assign it’s value to temp_node
Reference: Level Order Tree Traversal
时间: 2024-10-10 10:29:58