二叉树的层序遍历,返回二维list
//二叉树的层序遍历,返回二维list
public List<List<Character>> levelOrder(TreeNode root) {
List<List<Character>> ret = new ArrayList<>();
if(root == null){
return ret;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()){
int size = queue.size();
List<Character> curRow = new LinkedList<>();
while (size > 0){
TreeNode cur = queue.poll();
curRow.add(cur.val);
if(cur.left != null){
queue.offer(cur.left);
}
if(cur.right != null){
queue.offer(cur.right);
}
size--;
}
ret.add(curRow);
}
return ret;
}
testDemo:
public static void main(String[] args) {
TestBinaryTree testBinaryTree = new TestBinaryTree();
testBinaryTree.preOrder(testBinaryTree.creteTree());
System.out.println();
List<List<Character>> lists = testBinaryTree.levelOrder(testBinaryTree.creteTree());
for(List<Character> l:lists){
System.out.println(l);
}
}