从上到下打印二叉树

二叉树的层序遍历:

采用队列法

 public ArrayList PrintFromTopToBottom(TreeNode root){
        Queue queue =new ArrayDeque();
          ArrayList list  = new ArrayList();
        if(root==null){
            return list;
        }
          
          TreeNode cur = root;
          queue.add(cur);
          while(!queue.isEmpty()){
               cur =  queue.remove();
              list.add(cur.val);
                System.out.println(cur.val);
              if(cur.left!=null){
                  queue.add(cur.left);
              }
              if(cur.right!=null){
                  queue.add(cur.right);
              }   
          }  
        return list;
  }

 

你可能感兴趣的:(剑指offer,面试复习)