[算法学习]树的广度遍历

问题描述: 从上层向下层遍历,从左向右打印出一棵树 。

解法与分析: 广度遍历,按照从左向右的方式,我们可以使用队列来保存每一层的结点,每次结点出队,将出队结点的子结点入队,直至队列为空,就可以打印出符合要求的树遍历。


参考代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 从上层向下层遍历,从左向右
* @param root
*/

public static void printTreeFromTopTOBottom(TreeNode root)
{

if (root == null) return;

Queue<TreeNode> queue = new LinkedList<PrintTree.TreeNode>();
queue.offer(root);
while (!queue.isEmpty())
{
TreeNode node = queue.poll();
System.out.print(node.val + " ");
if (node.left != null)
{
queue.offer(node.left);
}
if (node.right != null)
{
queue.offer(node.right);
}
}
System.out.println();
}