二叉树的前中后序遍历和层序遍历对应深度优先和广度优先,深度优先就像前,中,后序一样一直往下走,直到走不下去,广度优先则是一层一层的走,按二叉树从上到下,从左到右依次打印每个节点中存储的数据。
/*1.层序遍历及其变形题
2.前中后序的非递归写法
*/
//层序遍历可以认为是二叉树的广度优先遍历(队列)
public static LevelOrder{
private static class Node{
char val;
Node left;
Node right;
Node(char val){
this.val=val;
}
}
public static void levelOrder(Node root){
//基本层序遍历中队列是不为空的
if(root==null){
return null;
}
Queue<Node> queue=new LinkedList<>();//用链表实现队列
queue.offer(root);
while(!queue.isEmpty()){
Node front=queue.poll();//取出队首元素
System.out.println(front.val);
if(front.left!=null){
queue.offer(front.left);//将front的左孩子带到队列中
}
if(front.right!=null){
queue.offer(front.right);//将front的右孩子带到队列中
}
}
}
private static class NodeLevel{
public Node node;
public int level;
NodeLevel(Node node,int level){
this.node=node;
this.level=level;
}
}
public static void levelOrder(Node root){
if(root==null){
return;
}
Queue<NodeLevel> queue =new LinkedList<>();
queue.offer(new NodeLevel(root,1));
while(!queue.isEmpty()){
NodeLevel front=queue.poll();
System.out.println(front.level+":"+front.node.val);
if(front.node.left!=null){
queue.offer(new NodeLevel(front.node.left,front.level+1));
}
if(front.node.right!=null){
queue.offer(new NodeLevel(front.node.right,front.level+1));//层序遍历并且带着层数
}
}
}
}
本文深入探讨了二叉树的遍历方法,包括前序、中序、后序及层序遍历,并通过实例代码详细解释了深度优先与广度优先遍历的实现过程。
1万+

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



