与树的前中后序遍历的DFS思想不同,层次遍历用到的是BFS思想。一般DFS用递归去实现(也可以用栈实现),BFS需要用队列去实现。
层次遍历的步骤是:
1.对于不为空的结点,先把该结点加入到队列中
2.从队中拿出结点,如果该结点的左右结点不为空,就分别把左右结点加入到队列中
3.重复以上操作直到队列为空
1 public class Solution{
2 class TreeNode {
3 int val;
4 TreeNode left;
5 TreeNode right;
6 TreeNode(int x) { val = x; }
7 }
8 public static void LaywerTraversal(TreeNode root){
9 if(root==null) return;
10 LinkedList<TreeNode> list = new LinkedList<TreeNode>();
11 list.add(root);
12 TreeNode currentNode;
13 while(!list.isEmpty()){
14 currentNode=list.poll();
15 System.out.println(currentNode.val);
16 if(currentNode.left!=null){
17 list.add(currentNode.left);
18 }
19 if(currentNode.right!=null){
20 list.add(currentNode.right);
21 }
22 }
23 }
24 }
本文详细介绍了二叉树的层次遍历算法,对比前中后序遍历的DFS思想,层次遍历采用BFS思想,利用队列实现。文章提供了具体的Java代码实现,展示了如何通过队列进行节点的逐层访问。
114

被折叠的 条评论
为什么被折叠?



