如下代码
import java.util.Stack;
/**
*
* @author Administrator
*
*/
class treenode {
private int data;
private treenode[] kNode;
public treenode(int data) {
super();
this.data = data;
}
/**
* @return the date
*/
public int getData() {
return data;
}
/**
* @param date
* the date to set
*/
public void setData(int data) {
this.data = data;
}
/**
* @return the kNode
*/
public treenode[] getkNode() {
return kNode;
}
/**
* @param kNode
* the kNode to set
*/
public void setkNode(treenode[] kNode) {
this.kNode = kNode;
}
}
public class k_tree {
public static void main(String[] args) {
// TODO Auto-generated method stub
treenode a = new treenode(1);
treenode b = new treenode(2);
treenode c = new treenode(3);
treenode d = new treenode(4);
treenode e = new treenode(5);
treenode f = new treenode(6);
treenode[] aNode = { b, c, d };
treenode[] bNode = { e, f };
a.setkNode(aNode);
b.setkNode(bNode);
System.out.println("递归遍历:");
displayTree(a);
System.out.println("非递归遍历:");
displayTreeByStack(a);
}
// 递归遍历;
static void displayTree(treenode root) {
if (root == null)
System.out.println("空树");
else {
if (root.getkNode() != null) {// 有子节点继续递归;
for (treenode tn : root.getkNode())
displayTree(tn);
}
System.out.println(root.getData());// 打印节点值;
}
}
// 非递归遍历利用栈模拟;
@SuppressWarnings({ "unchecked", "rawtypes" })
static void displayTreeByStack(treenode root) {
if (root == null)
System.out.println("空树");
else {
Stack allNode = new Stack();// 临时存储用栈
allNode.push(root);// 压入根节点
while (!allNode.isEmpty()) {// 只有栈不为空
treenode n = (treenode) allNode.pop();// 弹出元素
System.out.println(n.getData());
if (n.getkNode() != null) {// 再遍历压入子树
for (treenode tn : n.getkNode())
allNode.push(tn);
}
}
}
}
}