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

来源:互联网 发布:ubuntu terminal 主题 编辑:程序博客网 时间:2024/06/05 20:07

题目描述

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


分类:二叉树

解法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

原创粉丝点击