题目描述
给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
该二叉树层序遍历的结果是
[
[3],
[9,20],
[15,7]
]
做完这道题,可以继续做https://blog.csdn.net/m0_37564426/article/details/114397289(常考数据结构与算法:二叉树的之字形层序遍历)
示例1
输入
{1,2}
返回值
[[1],[2]]
示例2
输入
{1,2,3,4,#,#,5}
返回值
[[1],[2,3],[4,5]]
import java.util.ArrayList;
public class LevelOrderMe {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>();
}
ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>();
/**
*
* @param root TreeNode类
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
if(null == root){
return arrayLists;
}
levelOrder(root,0);
return arrayLists;
}
private void levelOrder (TreeNode root, int level) {
if(root == null){
return;
}
if(arrayLists.size() == level){
ArrayList arr = new ArrayList();
arr.add(root.val);
arrayLists.add(arr);
}else{
ArrayList arr = arrayLists.get(level);
arr.add(root.val);
}
if(null != root.left){
levelOrder(root.left,level+1);
}
if(null != root.right){
levelOrder(root.right,level+1);
}
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}