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

xiaoxiao2021-02-28  82

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。 分类:二叉树 解法1:使用队列来进行层次遍历即可。 [java]  view plain  copy import java.util.ArrayList;   /**  public class TreeNode {      int val = 0;      TreeNode left = null;      TreeNode right = null;        public TreeNode(int val) {          this.val = val;        }    }  */   public class Solution {       public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {           ArrayList<Integer> res = new ArrayList<Integer>();           if(root==nullreturn res;           ArrayList<TreeNode> queue = new ArrayList<TreeNode>();              queue.add(root);           while(!queue.isEmpty()){               TreeNode cur = queue.remove(0);               res.add(cur.val);               if(cur.left!=null){                   queue.add(cur.left);               }               if(cur.right!=null){                   queue.add(cur.right);               }           }           return res;       }   }  

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

转载请注明原文地址: https://www.6miu.com/read-96540.html

最新回复(0)