剑指offer--从上往下打印二叉树

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。


分类:二叉树

解法1:使用队列来进行层次遍历即可。
[java]  view plain  copy
  1. import java.util.ArrayList;  
  2. /** 
  3. public class TreeNode { 
  4.     int val = 0; 
  5.     TreeNode left = null; 
  6.     TreeNode right = null; 
  7.  
  8.     public TreeNode(int val) { 
  9.         this.val = val; 
  10.  
  11.     } 
  12.  
  13. } 
  14. */  
  15. public class Solution {  
  16.     public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {  
  17.         ArrayList<Integer> res = new ArrayList<Integer>();  
  18.         if(root==nullreturn res;  
  19.         ArrayList<TreeNode> queue = new ArrayList<TreeNode>();  
  20.            queue.add(root);  
  21.         while(!queue.isEmpty()){  
  22.             TreeNode cur = queue.remove(0);  
  23.             res.add(cur.val);  
  24.             if(cur.left!=null){  
  25.                 queue.add(cur.left);  
  26.             }  
  27.             if(cur.right!=null){  
  28.                 queue.add(cur.right);  
  29.             }  
  30.         }  
  31.         return res;  
  32.     }  
  33. }  


原文链接  http://blog.csdn.net/crazy__chen/article/details/44998621

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值