LeetCode | 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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
//层序遍历,使用队列来实现: //队列的前半部分是当前层节点,后半部分是下一层节点 //remove队头遍历其val,然后将其left与right(如果有的话)入队 //使用标记位nextLevelStarter来标记下一层的首个节点,以免在队列中遍历当前层时越界 public class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(root==null) return result; Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();//注意Java中Queue是接口,不能直接实例化,而LinkedList实现了Queue接口 nodeQueue.add(root); TreeNode nextLevelStarter; //标记下一层的起始节点,以免在Queue中遍历是越界 while(!nodeQueue.isEmpty()){ List<Integer> thisLevelList = new ArrayList<Integer>(); nextLevelStarter = null; //在开始遍历本层时,先把其置为null,然后找下一层的首节点赋予 while(nodeQueue.isEmpty()==false && nodeQueue.peek()!=nextLevelStarter){//在Queue中遍历本层的节点 TreeNode curNode = nodeQueue.remove(); //peek()只返回头,remove()返回并删除头 thisLevelList.add(curNode.val); if(curNode.left!=null) nodeQueue.add(curNode.left); if(curNode.right!=null) nodeQueue.add(curNode.right); if(nextLevelStarter==null){ //说明还未找到下层的首节点,就进入寻找 if(curNode.left!=null){ nextLevelStarter = curNode.left; }else if(curNode.right!=null){ nextLevelStarter = curNode.right; } } } result.add(thisLevelList); } return result; } }