Node结点的实现
class Node {
int value;
Node left;
Node right;
public Node(int value, Node left, Node right) {
this.value = value;
this.left = left;
this.right = right;
}
}
主要逻辑方法
private static void printNode(List<Node> nodes) {
List<Node> listT = new ArrayList<>();
for (Node node : nodes) {
System.out.print(node.value + ",");
if (node.left != null) {
listT.add(node.left);
}
if (node.right != null) {
listT.add(node.right);
}
}
// 判断当前层是否有节点加入listT中,如果有,则进行递归调用
if(!listT.isEmpty()) {
printNode(listT);
}
}
实现main的方法:
public static void main(String[] args) {
// leaf node
Node node4 = new Node(4, null, null);
Node node5 = new Node(5, null, null);
Node node6 = new Node(6, null, null);
Node node7 = new Node(7, null, null);
// node 2 and node 3
Node node2 = new Node(2, node4, node5);
Node node3 = new Node(3, node6, node7);
// root node
Node root = new Node(1, node2, node3);
List<Node> list = new ArrayList<>();
list.add(root);
printNode(list);
}