参考 https://blog.csdn.net/hansionz/article/details/81947834 c实现
参考 https://blog.csdn.net/weixin_40119167/article/details/96150882 java实现
方法一:使用两个辅助集合
1)使用list或者queue做缓存,创建两个缓存
-buffer:用来存储当前层的所有节点;
-bufferChildren,用来存储当前层的子节点;
2)遍历(并取出)buffer中节点值时,将左右子节点加入bufferChildren;
3)交替两个buffer;
4)判断buffer是否为null,如果非空:执行步骤2)3);否则结束遍历。
方法二:使用一个辅助集合
1)使用queue做缓存buffer,初始化时加入根节点;
2)出队buffer中节点,将左右子节点入队;
3)循环2)直到buffer为空,结束遍历。
代码如下:
public class Test {
public static void main(String[] args) {
Node tree = initBinaryTree();
traversal(tree);
traversal2(tree);
}
/**
* init tree
* <p>
* d0 1
* d1 2 | 3
* d2 4 4 5 9
* d3 6|7 8|9 10
* d4 11|12
*
* @return root of tree
*/
public static Node initBinaryTree() {
Node d11 = new Node(11, null, null);
Node d12 = new Node(12, null, null);
Node d6 = new Node(6, d11, d12);
Node d7 = new Node(7, null, null);
Node d8 = new Node(8, null, null);
Node d9 = new Node(9, null, null);
Node d10 = new Node(10, null, null);
Node d4 = new Node(4, d6, d7);
Node d4$ = new Node(4, null, null);
Node d5 = new Node(5, d8, d9);
Node d9$ = new Node(9, null, d10);
Node d2 = new Node(2, d4, d4$);
Node d3 = new Node(3, d5, d9$);
return new Node(1, d2, d3);
}
/**
* 方法1,使用两个辅助缓存结构
*
* @param root
*/
public static void traversal(Node root) {
if (root == null) {
return;
}
Queue<Node> buffer = new ArrayDeque<>();
buffer.add(root);
Queue<Node> bufferChild = new ArrayDeque<>();
Node left, right, node;
while (true) {
if ((node = buffer.poll()) != null) {
System.out.print(node.value + " ");
left = node.left;
right = node.right;
if (left != null) {
bufferChild.offer(left);
}
if (right != null) {
bufferChild.offer(right);
}
} else {
System.out.println();
Queue<Node> tmp = buffer;
buffer = bufferChild;
bufferChild = tmp;
if (buffer.size() == 0) {
break;
}
}
}
}
/**
* 方法2,使用一个辅助缓存结构
*
* @param root
*/
public static void traversal2(Node root) {
if (root == null) {
return;
}
Queue<Node> buffer = new ArrayDeque<>();
buffer.add(root);
Node left, right, node;
while (true) {
if ((node = buffer.poll()) != null) {
System.out.print(node.value + " ");
left = node.left;
right = node.right;
if (left != null) {
buffer.offer(left);
}
if (right != null) {
buffer.offer(right);
}
} else {
break;
}
}
}
/**
* binary tree node
*/
private static class Node {
private int value;
private Node left;
private Node right;
public Node(int value, Node left, Node right) {
this.value = value;
this.left = left;
this.right = right;
}
public int getValue() {
return value;
}
public Node setValue(int value) {
this.value = value;
return this;
}
public Node getLeft() {
return left;
}
public Node setLeft(Node left) {
this.left = left;
return this;
}
public Node getRight() {
return right;
}
public Node setRight(Node right) {
this.right = right;
return this;
}
}
}
运行结果为:
//二叉树结构见initBinaryTree()
//方法1运行结果
1
2 3
4 4 5 9
6 7 8 9 10
11 12
//方法2运行结果
1 2 3 4 4 5 9 6 7 8 9 10 11 12