问题:
把一个二叉树,安装从root到leaf的顺序把每一层上的node从左到右打印出来。
分析:
利用两个arraylist,一个arraylist装上一层的node, 另一个arraylist装上一层的child。如果上一层arraylist空了,两个arraylist互换。
代码:
//print the binary tree by level
public static void printByLevel(Node node) {
ArrayList<Node> list1 = new ArrayList<Node>();
ArrayList<Node> list2 = new ArrayList<Node>();
list1.add(node);
while(list1.size() != 0) {
for (int i = 0; i < list1.size(); i++) {
System.out.print(list1.get(i).value + " ");
if (list1.get(i).leftChild != null) list2.add(list1.get(i).leftChild);
if (list1.get(i).rightChild != null) list2.add(list1.get(i).rightChild);
}
System.out.println();
list1.clear();
ArrayList<Node> temp = list1;
list1 = list2;
list2 = temp;
}
}
class Node {
Node leftChild = null;
Node rightChild = null;
String name;
Node(String name) {
this.name = name;
}
}
转载请注明出处:http://blog.csdn.net/beiyeqingteng/
分享到:
相关推荐
二叉树模拟器.py二叉树模拟器.py二叉树模拟器.py二叉树模拟器.py二叉树模拟器.py二叉树模拟器.py二叉树模拟器.py二叉树模拟器.py二叉树模拟器.py二叉树模拟器.py二叉树模拟器.py二叉树模拟器.py二叉树模拟器.py...
数据结构的二叉树遍历 其中有二叉树的创建和二叉树的各种遍历方式...................................................................................
1.采用二叉链表作为存储结构,创建一棵...6.用递归公式计算二叉树的高度(BiTreeDepth(BT)=0; 当二叉树空时(BT==NULL)。 BiTreeDepth(BT)=max{ BiTreeDepth(BT->lchild), BiTreeDepth(BT->rchild)}+1;当二叉树不空时
ds18b20二叉树搜索算法.pdf
ds18b20二叉树搜索算法.doc
二叉树.R.r
二叉树遍历操作.cpp
二叉树遍历序列.cpp
线索化二叉树及对线索化二叉树的遍历.cpp
二叉树的遍历.doc 很好...............
c++数据结构 二叉树的遍历.ppt 详细描述二叉树的三种遍历方法
树与二叉树.ppt.zip
树和二叉树实验报告.pdf树和二叉树实验报告.pdf
实验3 二叉树的应用.pdf实验3 二叉树的应用.pdf
实验四 二叉树操作实现.docx实验四 二叉树操作实现.docx
实验四 二叉树操作实现.pdf实验四 二叉树操作实现.pdf
13、二叉树应用实验.docx13、二叉树应用实验.docx
数据结构二叉树的遍历.pdf
递归问题的二叉树求解方法.pdf