二叉树的先序,中序和后序遍历,这里要多看看数据结构。
package java21to30;
public class D21_BinaryCharTree {
char value;
D21_BinaryCharTree leftChild;
D21_BinaryCharTree rightChild;
public static void main(String[] args) {
D21_BinaryCharTree tree = manualConstructTree();
System.out.println("先序遍历:");
tree.preOrderVisit();
System.out.println("\r\n中序遍历:");
tree.inOrderVisit();
System.out.println("\r\n后序遍历:");
tree.postOrderVisit();
System.out.println("\r\n二叉树深度: " + tree.getDepth());
System.out.println("节点个数: " + tree.getNumNodes());
}
public D21_BinaryCharTree(char paraName) {
value = paraName;
leftChild = null;
rightChild = null;
}
public static D21_BinaryCharTree manualConstructTree() {
D21_BinaryCharTree result = new D21_BinaryCharTree('a');
D21_BinaryCharTree TreeB = new D21_BinaryCharTree('b');
D21_BinaryCharTree TreeC = new D21_BinaryCharTree('c');
D21_BinaryCharTree TreeD = new D21_BinaryCharTree('d');
D21_BinaryCharTree TreeE = new D21_BinaryCharTree('e');
D21_BinaryCharTree TreeF = new D21_BinaryCharTree('f');
D21_BinaryCharTree TreeG = new D21_BinaryCharTree('g');
D21_BinaryCharTree TreeH = new D21_BinaryCharTree('h');
D21_BinaryCharTree TreeI = new D21_BinaryCharTree('i');
result.leftChild = TreeB;
result.rightChild = TreeC;
TreeB.rightChild = TreeD;
TreeC.leftChild = TreeE;
TreeD.leftChild = TreeF;
TreeD.rightChild = TreeG;
TreeG.leftChild = TreeH;
TreeB.leftChild = TreeI;
return result;
}
public void preOrderVisit() {
System.out.print("" + value + " ");
if (leftChild != null) {
leftChild.preOrderVisit();
}
if (rightChild != null) {
rightChild.preOrderVisit();
}
}
public void inOrderVisit() {
if (leftChild != null) {
leftChild.inOrderVisit();
}
System.out.print("" + value + " ");
if (rightChild != null) {
rightChild.inOrderVisit();
}
}
public void postOrderVisit() {
if (leftChild != null) {
leftChild.postOrderVisit();
}
if (rightChild != null) {
rightChild.postOrderVisit();
}
System.out.print("" + value + " ");
}
public int getDepth() {
if ((leftChild == null) && (rightChild == null)) {
return 1;
}
int tempLeftDepth = 0;
if (leftChild != null) {
tempLeftDepth = leftChild.getDepth();
}
int tempRightDepth = 0;
if (rightChild != null) {
tempRightDepth = rightChild.getDepth();
}
if (tempLeftDepth >= tempRightDepth) {
return tempLeftDepth + 1;
} else {
return tempRightDepth + 1;
}
}
public int getNumNodes() {
if ((leftChild == null) && (rightChild == null)) {
return 1;
}
int tempLeftNodes = 0;
if (leftChild != null) {
tempLeftNodes = leftChild.getNumNodes();
}
int tempRightNodes = 0;
if (rightChild != null) {
tempRightNodes = rightChild.getNumNodes();
}
return tempLeftNodes + tempRightNodes + 1;
}
}
输出结果:
先序遍历:
a b i d f g h c e
中序遍历:
i b f d h g a e c
后序遍历:
i f h g d b e c a
二叉树深度: 5
节点个数: 9