笔试题:遍历二叉树之字形输出,即第一行从左到右输出,第二行从右到左输出
思路:层次遍历,记录标记
import lombok.Data;
import org.junit.Test;
import java.util.*;
public class LeeCodeTest {
@Data
public class Node {
private String value;
private Node leftChild;
private Node rightChild;
}
public void trace(ArrayDeque<Node> queue, int level) {
int size = queue.size();
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
Node head = queue.poll();
if (level % 2 == 0) {
list.add(head.value + "-");
} else {
list.add(0, head.value + "_");
}
if (head == null) {
return;
}
if (head.leftChild != null) {
queue.add(head.leftChild);
}
if (head.rightChild != null) {
queue.add(head.rightChild);
}
}
if (list.size() > 0) {
System.out.println(list.toString());
}
if (size > 0) {
trace(queue, level + 1);
}
}
@Test
public void testBiTreeTrace() {
ArrayDeque<Node> queue = new ArrayDeque<>();
Node parent = new Node();
parent.value = "1";
Node l1 = new Node();
l1.value = "2";
Node l2 = new Node();
l2.value = "3";
Node l3 = new Node();
l3.value = "5";
Node l4 = new Node();
l4.value = "4";
parent.leftChild = l1;
parent.rightChild = l2;
l2.rightChild = l3;
l2.leftChild = l4;
((ArrayDeque<Node>) queue).addFirst(parent);
trace(queue, 0);
}
}