Leetcode-102(Java) 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] ]
链接地址:https://leetcode.com/problems/binary-tree-level-order-traversal/
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> list = new LinkedList<List<Integer>>(); if(root == null) return list; //创建一个队列,用于存放所有节点 Queue<TreeNode> currentLevel = new LinkedList<TreeNode>(); currentLevel.add(root); while(!currentLevel.isEmpty()) { //创建一个List记录当前层所有节点值 List<Integer> currentList = new LinkedList<Integer>(); int size = currentLevel.size(); for(int i = 0; i < size; i++) { //poll()获取并移除此列表的头结点 TreeNode currentNode = currentLevel.poll(); currentList.add(currentNode.val); //记录每一层的节点值到List<Integer>中 if(currentNode.left != null) currentLevel.add(currentNode.left); if(currentNode.right != null) currentLevel.add(currentNode.right); //将当前List<Integer>添加到List<List<Integer>>中 } list.add(currentList); } return list; } }