package 蓝桥练习;
public class 二叉树层次遍历 {
public static int MAXSIZE = 100;
public static Node queue[] = new Node[MAXSIZE];
public static void main(String[] args) {
Node h = new Node(‘H‘, null, null);
Node i = new Node(‘I‘, null, null);
Node f = new Node(‘F‘, h, i);
Node g = new Node(‘G‘, null, null);
Node d = new Node(‘D‘, null, null);
Node e = new Node(‘E‘, null, null);
Node b = new Node(‘B‘, d, e);
Node c = new Node(‘C‘, f, g);
Node a = new Node(‘A‘, b, c);
level(a);
}
/**
* 层次遍历二叉树
* @param p
*/
private static void level(Node p) {
int front, rear;
front = rear = 0;
Node q;
if (p != null) {
rear = (rear + 1) % MAXSIZE;
queue[rear] = p;
while (front != rear) {
front = (front + 1) % MAXSIZE;
q = queue[front];
System.out.print(q.key + " ");
if (q.leftNode != null) {
rear = (rear + 1) % MAXSIZE;
queue[rear] = q.leftNode;
}
if (q.rightNode != null) {
rear = (rear + 1) % MAXSIZE;
queue[rear] = q.rightNode;
}
}
}
}
}
class Node {
public char key;
public Node leftNode;
public Node rightNode;
public Node(char key) {
this(key, null, null);
}
public Node(char key, Node leftNode, Node rightNode) {
this.key = key;
this.leftNode = leftNode;
this.rightNode = rightNode;
}
}
时间: 2024-10-05 16:13:39