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] ]
目前只能想到用一个二维数组先一层一层将树的节点存起来在逐层取出其val,空间效率不是很高,代码如下:
/** * 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>> re_list = new ArrayList<List<Integer>>(); List<List<TreeNode>> node_list = new ArrayList<List<TreeNode>>(); List<TreeNode> list = new ArrayList<TreeNode>(); if(root==null) return re_list;//如果根节点为空返回re_list list.add(root); node_list.add(list); int i = 0; boolean flag = true; while(flag){ flag = false; List<TreeNode> next_list = new ArrayList<TreeNode>(); list = node_list.get(i); for(TreeNode node:list){ if(node.left!=null) { next_list.add(node.left); flag = true; } if(node.right!=null) { next_list.add(node.right); flag = true; } } node_list.add(next_list); i++; } for(int j=0;j<node_list.size();j++){ List<Integer> temp_list = new ArrayList<Integer>(); list = node_list.get(j); for(int k=0;k<list.size();k++){ temp_list.add(list.get(k).val); } if(!temp_list.isEmpty()) re_list.add(temp_list); } return re_list; } }