您的位置:首页 > 编程语言 > Java开发

二叉树的java构建和三种遍历方式

2011-08-31 16:52 483 查看




二.代码,两个class

Java代码


public class Node {
/** 名称 */
private String name;

/** 左节点 */
private Node left;

/** 右节点 */
private Node right;

//get.set略
public Node(String n, Node l, Node r) {
name = n;
left = l;
right = r;
}
}

Java代码


public class Admin {
public static void main(String[] args) {
test();
}

private static void test() {
// 先序
xian(init());
System.out.println();
// 中序
zhong(init());
System.out.println();
// 后序
hou(init());
}

/** 初始化 */
private static Node init() {
Node nodeG = new Node("G", null, null);
Node nodeF = new Node("F", null, null);
Node nodeE = new Node("E", null, null);
Node nodeD = new Node("D", null, nodeG);
Node nodeC = new Node("C", nodeF, null);
Node nodeB = new Node("B", nodeD, nodeE);
Node nodeA = new Node("A", nodeB, nodeC);
return nodeA;
}

private static void print(Node node) {
System.out.print(node.getName() + "==>");
}

/** 先序 中->左->右 */
public static void xian(Node node) {
if (node != null) {
print(node);
xian(node.getLeft());
xian(node.getRight());
}
}

/** 中序 左->中->右 */
public static void zhong(Node node) {
if (node != null) {
zhong(node.getLeft());
print(node);
zhong(node.getRight());
}
}

/** 后序 左->右->中 */
public static void hou(Node node) {
if (node != null) {
hou(node.getLeft());
hou(node.getRight());
print(node);
}
}
}

转载地址:http://xiaojianhx.iteye.com/blog/491481
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: