给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例
给一棵二叉树 {3,9,20,#,#,15,7}
:
3
/ \
9 20
/ \
15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]
挑战
挑战1:只使用一个队列去实现它
挑战2:用DFS算法来做
解题思路:
利用一个队列来辅助层级遍历,先将root offer进队列,再poll出来,将当前poll出的元素存进list中,考察当前队列front元素是否有左右孩子,若有则将其左右孩子offer进队列中,循环操作,直到队列为空,则表明所有元素都按照层级关系存进list中。
注意本题需要的结果是保存在一个二维数组中,每一个层级的数据占据一行,所以单独对层级加一个一维数组temp暂存,再将temp存进res二维数组中。
注意queue是由LinkedList实现的,添加使用offer(),删除使用poll(),返回队首的元素peek().
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: A Tree
* @return: Level order a list of lists of integer
*/
public List<List<Integer>> levelOrder(TreeNode root) {
// write your code here
if(root == null)
return null;
List<List<Integer>> res = new ArrayList<>();
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
ArrayList<Integer> temp = new ArrayList<>();
for(int i=0 ; i<len ; i++){
TreeNode node = queue.poll();
temp.add(node.val);
if(node.left != null)
queue.offer(node.left);
if(node.right != null)
queue.offer(node.right);
}
res.add(temp);
}
return res;
}
}