原题链接在这里:https://leetcode.com/problems/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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
题解:
是一道BFS,利用queue,先进先出,并利用curCount来判断是否走完了当前一层。当curCount = 0 时表示当前一层走完,要把当前list加入res里,再刷新list,问题是不要忘记同时刷新curCount和nextCount.
Time Complexity: O(n). Space: O(n).
AC Java:
/** * 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>> res = new ArrayList<List<Integer>>(); if(root == null){ return res; } LinkedList<TreeNode> que = new LinkedList<TreeNode>(); que.add(root); int curCount = 1; int nextCount = 0; List<Integer> item = new ArrayList<Integer>(); while(!que.isEmpty()){ TreeNode tn = que.poll(); item.add(tn.val); curCount--; if(tn.left != null){ que.add(tn.left); nextCount++; } if(tn.right != null){ que.add(tn.right); nextCount++; } if(curCount == 0){ res.add(new ArrayList<Integer>(item)); item = new ArrayList<Integer>(); curCount = nextCount; nextCount = 0; } } return res; } }
类似的有Check Completeness of a Binary Tree.