https://oj.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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
解题思路:
这题和前面求最浅深度的题目 Minimum Depth of Binary Tree 一个思路,在广度便利的基础上,分清层次就可以了。广度遍历使用了队列的数据结构,当前节点的左右子几点如果不为null,将他们都塞入队列尾,然后从队列头取出一个元素。循环操作。
/** * Definition for binary tree * 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>> returnList = new ArrayList<List<Integer>>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); if(root == null){ return returnList; }else{ queue.offer(root); } while(queue.size() != 0){ int size = queue.size(); List<Integer> list = new ArrayList<Integer>(); while(size > 0){ root = queue.poll(); list.add(root.val); if(root.left != null){ queue.offer(root.left); } if(root.right != null){ queue.offer(root.right); } size--; } returnList.add(list); } return returnList; } }
下面是一个递归方法的实现,这种写法比较少,因为遍历写易于理解,也简单。
思路是,递归实现了一个preorder的算法,但是呢,visit(node)的时候,把他们的level同时记录下来了,也就是在resultList中的下标,这样就可以对于本层的节点,直接list.get(level).add(root.val)即可。注意的是,如果当前level +1 比list的size还大,就要创建一个新的list。因为level从0开始,而size从1开始。最后,递归结束的条件是,root为空。
/** * Definition for binary tree * 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>> resultList = new ArrayList<List<Integer>>(); levelOrderHelper(root, 0, resultList); return resultList; } public void levelOrderHelper(TreeNode root, int level, List<List<Integer>> list){ if(root == null){ return; } if(level + 1 > list.size()){ list.add(new ArrayList<Integer>()); } list.get(level).add(root.val); levelOrderHelper(root.left, level + 1, list); levelOrderHelper(root.right, level + 1, list); } }
这个递归的方法借用了DFS,实现了BFS输出,还是很巧妙的,要细细体会。