代码实现:
import java.util.Scanner;
public class erChaShu {
private static int MAX_LEVEL;
public static void main(String[] args) {
// Node1<Integer> tree = new Node1();
//输入具体的数值控制树的深度
Scanner set = new Scanner(System.in);
int n = set.nextInt();
// tree.setValue(1);//将值加入节点中
//
// Node1<Integer> n = new Node1();
// n.setValue(2);
// tree.setLeft(n);
//
// n = new Node1();
// n.setValue(3);
// tree.setRight(n);
//
// n = new Node1();
// n.setValue(4);
// tree.getLeft().setLeft(n);
//
// n = new Node1();
// n.setValue(5);
// tree.getLeft().setRight(n);
Node1<Integer> tree = geterNode1();
for (int i = 0; i < n; i++) {
System.out.println("第"+i+"个小球的路径");
walk(tree);
}
}
//设置小球开关并往下走
private static void walk(Node1<Integer> node) {
if (node.getSwitcher() == 0) {
walk(node.getLeft());
node.setSwitcher(1);
}else {
walk(node.getRight());
node.setSwitcher(0);
}
}
//先序遍历
private static void preOrder(Node1<Integer> tree) {
if (tree == null) {
return;
}
System.out.println(tree.getValue()+"");
preOrder(tree.getLeft());
preOrder(tree.getRight());
}
//中序遍历
private static void inOrder(Node1<Integer> tree) {
if (tree ==null) {
return;
}
preOrder(tree.getLeft());
System.out.println(tree.getValue()+"");
preOrder(tree.getRight());
}
//后序遍历
private static void posOrder(Node1<Integer> tree) {
if (tree == null) {
return;
}
preOrder(tree.getLeft());
preOrder(tree.getRight());
System.out.println(tree.getValue()+"");
}
//创造根节点
private static Node1<Integer> geterNode1() {
Node1<Integer> node = new Node1<Integer>();
//将根节点的值设为1
node.setValue(1);
//传参到下一个方法生成左右子节点
generaNode1(2,node);
return node;
}
private static void generaNode1(int level,Node1<Integer> parent){
//如果节点的数目超过4层则迭代停止
if (level > 4) {
return;
}
int value = parent.getValue();
Node1<Integer> node = new Node1<Integer>();
//巡回找左孩子
node.setValue(value * 2);
parent.setLeft(node);
node = new Node1<>();
//巡回找右孩子
node.setValue(value * 2 + 1);
parent.setRight(node);
//再生成下一层节点
generaNode1(level + 1, parent.getLeft());
generaNode1(level + 1, parent.getRight());
}
}
class Node1<T>{
private T value;//节点的值
private int switcher;//小球通过的开关,0表示开关关闭,1表示开关打开
//设置左右节点
private Node1<T> left;
private Node1<T> right;
public Node1<T> getLeft() {
return left;
}
public void setLeft(Node1<T> left) {
this.left = left;
}
public Node1<T> getRight() {
return right;
}
public void setRight(Node1<T> right) {
this.right = right;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public int getSwitcher() {
return switcher;
}
public void setSwitcher(int switcher) {
this.switcher = switcher;
}
}