今天遇到一个面试题,构建一个二叉树,并分别打印四个分支。
import java.util.LinkedList;
import java.util.List;
public class BinaryTree {
private String[] array = { "A", "B", "C", "D", "E", "F", "G" };
private static List<Node> nodeList = null;
private static class Node {
Node leftChild;
Node rightChild;
String data;
Node(String newData) {
leftChild = null;
rightChild = null;
data = newData;
}
}
public void createBinTree() {
nodeList = new LinkedList<Node>();
for (int i = 0; i < array.length; i++) {
nodeList.add(new Node(array[i]));
}
for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) {
// 左
nodeList.get(parentIndex).leftChild = nodeList
.get(parentIndex * 2 + 1);
// 右
nodeList.get(parentIndex).rightChild = nodeList
.get(parentIndex * 2 + 2);
}
//last父节点
int lastParentIndex = array.length / 2 - 1;
//这里可以加判断,因为这里只有7个所以直接写了。
nodeList.get(lastParentIndex).leftChild = nodeList.get(lastParentIndex * 2 + 1);
nodeList.get(lastParentIndex).rightChild = nodeList.get(lastParentIndex * 2 + 2);
}
/**
* 遍历
*/
public static void post1(Node root) {
if (root == null)
return;
System.out.print(root.data);
post1(root.leftChild);
}
public static void post3(Node root) {
if (root == null)
return;
System.out.print(root.data);
post2(root.rightChild);
}
public static void post2(Node root) {
if (root == null)
return;
System.out.print(root.data);
post3(root.leftChild);
}
public static void post4(Node root) {
if (root == null)
return;
System.out.print(root.data);
post4(root.rightChild);
}
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.createBinTree();
Node root = nodeList.get(0);
// 输出
post1(root);
System.out.println();
post2(root);
System.out.println();
post3(root);
System.out.println();
post4(root);
}
}
效果: