层序遍历:即把一颗二叉树从上到下,从左到右遍历并打印
这里我们可以想到用队列,先放进去的先出来,把二叉树的每一层都依次保存到队列中
public class BinaryTree {
public static class BTNode {
//定义属性
public BTNode left;
public BTNode right;
int val;
public BTNode(int val) {
this.val = val;
}
public BTNode(BTNode left, BTNode right, int val) {
this.left = left;
this.right = right;
this.val = val;
}
}
BTNode root;//指向根结点
//创建一棵树void creatTree() {
BTNode node1 = new BTNode(11);
BTNode node2 = new BTNode(22);
BTNode node3 = new BTNode(33);
BTNode node4 = new BTNode(44);
BTNode node5 = new BTNode(55);
BTNode node6 = new BTNode(66);
node1.left = node2;
node1.right = node4;
node2.left = node3;
node4.left = node5;
node4.right = node6;
root=node1;
}
//层序遍历
public void levelorder(){
if(root==null){
return ;
}
Queue<BTNode> s=new LinkedList<>();
s.offer(root);
while(!s.isEmpty()){
BTNode cur=s.poll();
System.out.print(cur.val+" ");
if(cur.left!=null){
s.offer(cur.left);
}
if(cur.right!=null){
s.offer(cur.right);
}
}
}
public static void main(String[] args) {
BinaryTree bt=new BinaryTree();
System.out.println("============================");
System.out.println("层序遍历:");
bt.levelorder();
}
}
#二叉树的层序遍历, 返回二维List(题目描述如下)
和上道题本质一样,不同之处在于,这里要求从从下到上输出每一层的节点值。
除了输出顺序不同以外,这两道题的思路是相同的,
public void levelOder() { //公共的,没有参数,好调用
List<List<Integer>> as=levelOder(root);
System.out.println(as);
}
private List<List<Integer>> levelOder(BTNode root){
List<List<Integer>> list = new ArrayList<>();
//(1)为空时返回[],即创建的空数组if(root==null){
return list;
}
//(2)用队列循环保存每一层,并存在数组里Queue<BTNode> s = new LinkedList<>();
s.offer(root);
while(!s.isEmpty()){
int levelsize=s.size();
//创建新数组,即内部数组List<Integer> levelVal=new ArrayList<>();
for(int i=0;i<levelsize;i++){
BTNode cur=s.poll();
levelVal.add(cur.val);//把队列中存的元素拿到数组中保存//循环遍历左右字数if(cur.left!=null){
s.offer(cur.left);
}
if(cur.right!=null){
s.offer(cur.right);
}
}
list.add(levelVal);//把内部数组存放到外面那个大数组中
}
return list;//返回数组
}