层次遍历二叉树
1. 普通层次遍历
public static void levelOrder(TreeNode root) {
if (root == null) return;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode temp = queue.remove();
System.out.print(temp.getData() + "\t");
if (temp.getLeftChild() != null) queue.offer(temp.getLeftChild());
if (temp.getRightChild() != null) queue.offer(temp.getRightChild());
}
}
2. 每层换行的层次遍历
public static void levelByLevelOrder(TreeNode root) {
if (root == null) return;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int needPrintln = 1;
int levelNodeNum = 0;
while (!queue.isEmpty()) {
TreeNode temp = queue.remove();
System.out.print(temp.getData() + "\t");
if (temp.getLeftChild() != null) {
queue.offer(temp.getLeftChild());
levelNodeNum++;
}
if (temp.getRightChild() != null) {
queue.offer(temp.getRightChild());
levelNodeNum++;
}
needPrintln--;
if (needPrintln == 0) {
System.out.println();
needPrintln = levelNodeNum;
levelNodeNum = 0;
}
}
}
3. Z字形的层次遍历
public static void zLevelOrder(TreeNode root) {
if (root == null) return;
List<Stack<TreeNode>> stacks = new ArrayList<Stack<TreeNode>>();
stacks.add(new Stack<TreeNode>());
stacks.add(new Stack<TreeNode>());
int current = 0;
int next = 1;
stacks.get(current).push(root);
while (!stacks.get(0).isEmpty() || !stacks.get(1).isEmpty()) {
TreeNode temp = stacks.get(current).pop();
System.out.print(temp.getData()+"\t");
if (current == 0) {
if (temp.getLeftChild() != null)
stacks.get(next).push(temp.getLeftChild());
if (temp.getRightChild() != null)
stacks.get(next).push(temp.getRightChild());
} else {
if (temp.getRightChild() != null)
stacks.get(next).push(temp.getRightChild());
if (temp.getLeftChild() != null)
stacks.get(next).push(temp.getLeftChild());
}
if(stacks.get(current).isEmpty()){
System.out.println();
current=1-current;
next=1-next;
}
}
}