import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型ArrayList<ArrayList<>>
*/
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
// write code here
if(root == null){
return res;
}
count(root,0);
return res;
}
public void count(TreeNode node,int level){
if(level == res.size()){
res.add(new ArrayList<Integer>());
}
ArrayList<Integer> list = res.get(level);
list.add(node.val);
if(node.left != null){
count(node.left,level + 1);
}
if(node.right != null){
count(node.right,level+1);
}
}
}
【牛客网-名企高频面试题】 NC15 求二叉树的层序遍历
最新推荐文章于 2022-03-24 16:43:58 发布