分析
难度 中
来源
https://leetcode.com/problems/binary-tree-level-order-traversal/
题目
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
解答
1 package LeetCode; 2 3 import java.util.*; 4 5 public class L102_BinaryTreeLevelOrderTraversal { 6 public TreeNode makeBinaryTreeByArray(Integer[] array,int index){ 7 if(index<array.length&&array[index]!=null){ 8 int value=array[index]; 9 TreeNode t=new TreeNode(value); 10 array[index]=0; 11 t.left=makeBinaryTreeByArray(array,index*2+1); 12 t.right=makeBinaryTreeByArray(array,index*2+2); 13 return t; 14 }else 15 return null; 16 } 17 18 public List<List<Integer>> levelOrder(TreeNode root) { 19 List<Integer> levelList=new ArrayList<Integer>(); 20 List<List<Integer>> result=new ArrayList<List<Integer>>(); 21 if(root==null){ 22 return result; 23 } 24 Queue<TreeNode> queue=new LinkedList<TreeNode>(); 25 queue.offer(root); 26 int curCount=1;//记录当前层节点数 27 int nextCount=0;//记录下一层节点数 28 int outCount=0;//记录出队列节点数 29 while(!queue.isEmpty()){ 30 TreeNode node=queue.poll(); 31 levelList.add(node.val); 32 outCount++; 33 if(node.left!=null){ 34 queue.offer(node.left); 35 nextCount++; 36 } 37 if(node.right!=null){ 38 queue.offer(node.right); 39 nextCount++; 40 } 41 if(outCount==curCount)//当前层全部出队列 42 { 43 if(!levelList.isEmpty()) 44 result.add(levelList); 45 levelList=new ArrayList<Integer>(); 46 curCount=nextCount; 47 nextCount=0; 48 outCount=0; 49 } 50 } 51 return result; 52 } 53 54 public static void main(String[] args){ 55 L102_BinaryTreeLevelOrderTraversal l102=new L102_BinaryTreeLevelOrderTraversal(); 56 Integer[] values={1,2,3,4,5,6,7}; 57 TreeNode root=l102.makeBinaryTreeByArray(values,0); 58 List<List<Integer>> res=l102.levelOrder(root); 59 System.out.println(res.toString()); 60 } 61 }