Binary Tree Level Order Traversal Total Accepted: 51429 Total Submissions: 174478
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]
]
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
Hide Tags: Tree Breadth-first Search(广度优先遍历)
解题思路:
广度遍历而且要记录每一层。广度遍历利用队列实现,记录用列表实现
使用一个列队,一个列表。 列队用于记录每一层节点,列表用于存储每一层的节点
/** * Definition for a binary tree node. * public class TreeNode * { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> list=new LinkedList<List<Integer>>(); //如果根节点为空,返回list if(root==null) { return list; } //创建一个列队Queue<TreeNode>,用于存放所有节点 Queue<TreeNode> currentlevel=new LinkedList<TreeNode>(); currentlevel.add(root); while (!currentlevel.isEmpty()) { //创建一个List<Integer>用于记录当前层所有节点的值 List<Integer> currentList=new LinkedList<Integer>(); //size为当前层节点的个数 int size=currentlevel.size(); for (int i = 0; i < size; i++) { //poll()获取并移除此列表的头(第一个元素) TreeNode currentNode=currentlevel.poll(); //记录每一层的节点值到List<Integer>中 currentList.add(currentNode.val); 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; }
时间: 2024-12-10 05:30:48