码迷,mamicode.com
首页 > 其他好文 > 详细

BFS visit tree

时间:2015-09-24 07:06:24      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

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

 

BFS visit tree

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4834080.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!