标签:nod null turn style linked val list root queue
分析:层次遍历的经典算法
import java.util.ArrayList; import java.util.*; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer> >list=new ArrayList<ArrayList<Integer> >(); if(pRoot==null) return list; int layer=1; Queue<TreeNode>q=new LinkedList<>(); q.offer(pRoot); while(!q.isEmpty()){ int count=q.size(); ArrayList<Integer> temp=new ArrayList<>(); while(count>0){ TreeNode node=q.poll(); temp.add(node.val); if(node.left!=null) q.offer(node.left); if(node.right!=null) q.offer(node.right); count--; } layer++; list.add(temp); } return list; } }
树5:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
标签:nod null turn style linked val list root queue
原文地址:https://www.cnblogs.com/xuechengmeigui/p/12638210.html