Q60:把二叉树打印成多行

importjava.util.LinkedList;
importjava.util.Queue;
importBinaryTree.BinaryTreeNode;
public class Q60把二叉树打印成多行 {
   /**
    * 题目:把二叉树打印成多行
    * 题目说明:从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
    * 解题思路:利用层次遍历算法,设置变量last指向当前层的最后一个结点,设置变量count记录当前层已经访问的结点个数,当count和last相等时,表示该层访问结束。
    */
   public static void main(String[] args) {
      BinaryTreeNode root = new BinaryTreeNode();
      BinaryTreeNode node1 = new BinaryTreeNode();
      BinaryTreeNode node2 = new BinaryTreeNode();
      BinaryTreeNode node3 = new BinaryTreeNode();
      BinaryTreeNode node4 = new BinaryTreeNode();
      BinaryTreeNode node5 = new BinaryTreeNode();
      BinaryTreeNode node6 = new BinaryTreeNode();
     
      root.leftNode = node1;
      root.rightNode = node2;    
      node1.leftNode = node3;
      node1.rightNode = node4;   
      node2.leftNode = node5;
      node2.rightNode = node6;
     
      root.value = 8;
      node1.value = 6;
      node2.value = 10;
      node3.value = 5;
      node4.value = 7;
      node5.value = 9;
      node6.value = 11;
      Q60把二叉树打印成多行 test = new Q60把二叉树打印成多行();
      test.PrintBinaryTreeNode(root);
   }
   public static void PrintBinaryTreeNode(BinaryTreeNode root){
      if(root == null){
         return ;
      }
      Queue<BinaryTreeNode> queue = new LinkedList<BinaryTreeNode>();
      queue.add(root);//添加root到queue中
      int nextLevel = 0;
      int toBePrint = 1;
     
      while(!queue.isEmpty()){
         BinaryTreeNode curNode = queue.peek();//peek()只是获取队列首元素
         System.out.print(curNode.value + " ");
        
         if(curNode.leftNode != null){
            queue.add(curNode.leftNode);
            nextLevel ++;
         }
         if(curNode.rightNode != null){
            queue.add(curNode.rightNode);
            nextLevel ++;
         }
        
         queue.poll();//删除队列首元素
         toBePrint --;//将要打印的元素数目减1
         if(toBePrint == 0){
            System.out.println();
            toBePrint = nextLevel;
            nextLevel = 0;
         }
      }
   }
}
packageBinaryTree;
public class BinaryTreeNode {
   public int value;//此出要为非static的
   public BinaryTreeNode leftNode;
   public BinaryTreeNode rightNode; 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值