[LeetCode] 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]
]
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
思路
这道题可以这么做:用一个队列来保存每层节点,遍历该层所有节点同时将每个节点加到结果中,同时将每个节点的子女节点用一个list保存下来,遍历完本层节点后,将保存的子女节点加到队列中继续遍历。直到子女节点为空(也就是队列为空)为止
代码
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { // Note: The Solution object is instantiated only once and is reused by each test case. ArrayList<ArrayList<Integer>> ans=new ArrayList<ArrayList<Integer>>(); if(root==null) return ans; Queue<TreeNode> list=new LinkedList<TreeNode>(); list.add(root); while(!list.isEmpty()) { ArrayList<TreeNode> levelNodes=new ArrayList<TreeNode>(); ArrayList<Integer> res=new ArrayList<Integer>(); while(!list.isEmpty()) { TreeNode node=list.poll(); if(node.left!=null) levelNodes.add(node.left); if(node.right!=null) levelNodes.add(node.right); res.add(node.val); } list.addAll(levelNodes); ans.add(res); } return ans; } }
作者:Leo-Yang
原文都先发布在作者个人博客:http://www.leoyang.net/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.