题目:
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]
]
题意:
给定一棵二叉树,按照层顺序遍历二叉树所有的节点(即 从左向右 一层层地)
比如,给定二叉树{3,9,20,#,#,15,7}
,
3 / 9 20 / 15 7返回它的层遍历为:
[
[3],
[9,20],
[15,7]
]
算法分析:
该题是对二叉树进行层次优先遍历,层次遍历主要采用队列的形式进行存储,通过将每个节点的左孩子和右孩子放入队列中,然后每次从队列中取出元素即可。比较好理解,直接上代码了。
AC代码:
public class Solution { private static TreeNode root; public static ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if (root == null) { return res; } ArrayList<Integer> tmp = new ArrayList<Integer>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); int num; boolean reverse = false; while (!queue.isEmpty()) { num = queue.size(); //每次通过这个确定最终的出队数目 tmp.clear(); for (int i = 0; i < num; i++) //队列中出1个父,进两个子;出2个父,进4个子;出4个父,进8个子 { TreeNode node = queue.poll(); tmp.add(node.val); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } res.add(new ArrayList<Integer>(tmp)); } return res; } }
版权声明:本文为博主原创文章,转载注明出处
[LeetCode][Java] Binary Tree Level Order Traversal
原文:http://blog.csdn.net/evan123mg/article/details/46973341