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.
解题思路:
BFS
与Leetcode Binary Tree Level Order Traversal II 的差别只有一个从最上层显示到最底层,一个从最底层显示到最上层。
Java code:
/** * 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>> result = new ArrayList<List<Integer>>(); if(root == null){ return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while(!queue.isEmpty()){ int size = queue.size(); List<Integer> numberList = new ArrayList<Integer>(); while(size > 0){ TreeNode x = queue.remove(); numberList.add(x.val); if(x.left != null) { queue.add(x.left); } if(x.right != null){ queue.add(x.right); } size--; } result.add(numberList); } return result; } }