# 【死磕算法系列】二叉树的层次遍历

            a
/   \
b      c
/   \   /  \
d    e  f    g
/
h
\
i

a
b   c
d   e   f   g
h
i

java实现：

public void levelTraverse(TreeNode node){
if(node == null){
return;
}
int cur,last;
TreeNode current=null;
while(!queue.isEmpty()){
cur=0;
last=queue.size();
while(cur<last){
cur++;
current=queue.poll();
System.out.print(current.val+"\t");
if(current.left!=null){
}
if(current.right!=null){
}
}
System.out.println();
}
}

a
b   c
d   e   f   g
h
i

    public ArrayList<String> levelTraverseV2(TreeNode node){
ArrayList<String> list=new ArrayList<String>();
if(node == null){
return list;
}
int cur,last;
TreeNode current=null;
while(!queue.isEmpty()){
cur=0;
last=queue.size();
while(cur<last){
cur++;
current=queue.poll();
if(current.left!=null){
}
if(current.right!=null){
}
}
}

return list;
}

[a, b, c, d, e, f, g, h, i]

    public ArrayList< ArrayList<String>> levelTraverseV3(TreeNode node){
ArrayList< ArrayList<String>> list=new ArrayList< ArrayList<String>>();
if(node == null){
return list;
}
int cur,last;
TreeNode current=null;
while(!queue.isEmpty()){
cur=0;
last=queue.size();
ArrayList<String> level=new ArrayList<String>();
while(cur<last){
cur++;
current=queue.poll();
if(current.left!=null){
}
if(current.right!=null){
}
}
}

return list;
}

[[a], [b, c], [d, e, f, g], [h], [i]]

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120