TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
一.树
二.代码,两个class public class Node {
/** 名称 */
private String name;
/** 左节点 */
private Node left;
/** 右节点 */
private Node right;
[/code]
//get.set略
public Node(String n, Node l, Node r) { name = n; left = l; right = r; } } 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);
}
}
}[/code] 三.结果 A==>B==>D==>G==>E==>C==>F==>
D==>G==>B==>E==>A==>F==>C==>
G==>D==>E==>B==>F==>C==>A==>
源码下载:http://file.javaxxz.com/2014/11/9/000430171.zip |
|