上传的网站打不开,搜索推广平台有哪些,淘宝官网首页登录账号,wordpress微信登录设置从上往下打印二叉树的每个节点#xff0c;同一层的节点按照从左到右的顺序打印。例如输入下图的二叉树#xff0c;则一次打印出8#xff0c;6#xff0c;10#xff0c;5#xff0c;7#xff0c;9#xff0c;11。
思路#xff1a;利用队列,将左右子树加入队列末尾同一层的节点按照从左到右的顺序打印。例如输入下图的二叉树则一次打印出861057911。
思路利用队列,将左右子树加入队列末尾取出结点
代码
package offer;
import java.util.LinkedList; import java.util.Queue;
class BineryTree { int val; BineryTree left null; BineryTree right null; BineryTree(int val) { this.val val; } } public class ti32 { static void BineryTreeToQueue(BineryTree head) { if(headnull) { return; } QueueBineryTree queue new LinkedListBineryTree(); queue.add(head); while(!queue.isEmpty()) { BineryTree x queue.poll(); System.out.println(x.val); if(x.left!null) { queue.add(x.left); } if(x.right!null) { queue.add(x.right); } } } public static void main(String[] args) { BineryTree a new BineryTree(8); BineryTree b new BineryTree(6); BineryTree c new BineryTree(10); BineryTree d new BineryTree(5); BineryTree e new BineryTree(7); BineryTree f new BineryTree(9); BineryTree g new BineryTree(11); a.left b; a.right c; b.left d; b.right e; c.left f; c.right g; BineryTreeToQueue(a); } }题目三 请实现一个函数按照之字形打印二叉树即第一行按照从左到右的顺序打印第二层按照从右至左的顺序打印第三行按照从左到右的顺序打印其他行以此类推。
代码
package offer;
import java.util.ArrayList; import java.util.Stack;
class BineryTree { int val; BineryTree left null; BineryTree right null; BineryTree(int val) { this.val val; } } public class ti32 { static ArrayListArrayListInteger BineryTreeToQueue(BineryTree head) { ArrayListArrayListInteger alist new ArrayList(); if(headnull) { return alist; } StackBineryTree stack1 new StackBineryTree(); StackBineryTree stack2 new StackBineryTree(); stack1.add(head); while(!stack1.empty()||!stack2.empty()) { ArrayListInteger list new ArrayList(); if(!stack1.empty()) { while(!stack1.empty()) { BineryTree x stack1.pop(); list.add(x.val); if(x.left!null) { stack2.add(x.left); } if(x.right!null) { stack2.add(x.right); } } } else { while(!stack2.empty()) { BineryTree x stack2.pop(); list.add(x.val); if(x.right!null) { stack1.add(x.right); } if(x.left!null) { stack1.add(x.left); } } } alist.add(list); } return alist; } public static void main(String[] args) { BineryTree a new BineryTree(8); BineryTree b new BineryTree(6); BineryTree c new BineryTree(10); BineryTree d new BineryTree(5); BineryTree e new BineryTree(7); BineryTree f new BineryTree(9); BineryTree g new BineryTree(11); a.left b; a.right c; b.left d; b.right e; c.left f; c.right g; ArrayListArrayListInteger alist BineryTreeToQueue(a); for(int i0;ialist.size();i) { for(int j0;jalist.get(i).size();j) { System.out.print(alist.get(i).get(j) ); } System.out.println(); } } }