Tree level order--DFS /Queue
作者:互联网
public class Solution{
public List<List<Integer>> levelOrder( TreeNode root){
List<List<Integer>> res= new ArrayList<>();
if(root==null) return res;
dfs(res, root,0);
return res;
}
private void dfs( List<List<Integer>res, TreeNode root, int depth){
if(root==null) return;
if(depth>=res.size())
res.add( new LinkedList<>.();
res.get(depth).add(root.val);
dfs(res,root.left, depth+1);
dfs(res,root.right,depth+1);
=======================================================
public void PrintNodeByLevel( Node root){
if(root==null) return;
Queue<Node> q= new ArrayDeque<Node>();
while(!q.isEmpty()){
int size=q.size();
for(int i=0;i<size;i++){
Node n=q.poll();
if(n.left !=null) q.offer(n.left);
if(n.right !=null) q.offer(n.right);
System.out.print(n.val+"");
}
System.out.println();
}}
标签:return,level,--,res,Tree,dfs,depth,null,root 来源: https://www.cnblogs.com/LLflag1/p/16504273.html