package chap10;
import static org.junit.Assert.*;
import java.util.Stack;
import org.junit.Test;
public class exec10_4_3 {
/**
* 将该树打印
*
* @param tree
*/
static void printTree(Tree tree) {
Root root = tree.root;
if (root != null) {
Node node = root.node;
printNode(node);
}
}
/**
* 遍历一个树的非递归方法,用一个栈实现
*
* @param node
*/
static void printNode(Node node) {
Stack<Node> nodes = new Stack<Node>();
do {
if (node != null) {
System.out.println(node.key);
if (node.right != null) {
nodes.push(node.right);
}
node = node.left;
} else {
node = nodes.pop();
}
} while (nodes != null);
}
/**
* 创建一个树,弱智方法
*
* @return
*/
static Tree creatTree() {
Tree t = new Tree();
Root r = new Root();
Node n1, n2, n3, n4, n5, n6, n7, n8, n9, n0;
n1 = new Node(0);
n2 = new Node(1);
n3 = new Node(2);
n4 = new Node(3);
n5 = new Node(4);
n6 = new Node(5);
n7 = new Node(6);
n8 = new Node(7);
n9 = new Node(8);
n0 = new Node(9);
t.root = r;
r.node = n0;
n0.left = n1;
n0.right = n2;
n1.left = n3;
n1.right = n4;
n2.left = n5;
n2.right = n6;
n3.left = n7;
n4.left = n8;
n5.right = n9;
return t;
}
@Test
public void testName() throws Exception {
Tree t1 = creatTree();
printTree(t1);
}
}