二叉樹的按層列印與ZigZag列印
阿新 • • 發佈:2021-10-13
連結
給定一顆二叉樹,分別實現按層和 ZigZag 列印二叉樹。
ZigZag遍歷: 意思是第一層從左到右遍歷,第二層從右到左遍歷,依次類推。
心之所向,素履以往 生如逆旅,一葦以航import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { static class Node { Node left; Node right; int val; public Node(int val) { this.val = val; } } private static void printByLevel(Node root) { if (root == null) { return; } Queue<Node> queue = new LinkedList<>(); queue.offer(root); System.out.print("Level 1 :"); int currentLevel = 1; Node currentEnd = root, nextEnd = null; while (!queue.isEmpty()) { Node node = queue.poll(); System.out.print(" " + node.val); if (node.left != null) { queue.offer(node.left); nextEnd = node.left; } if (node.right != null) { queue.offer(node.right); nextEnd = node.right; } if (node == currentEnd && !queue.isEmpty()) { currentEnd = nextEnd; System.out.println(); System.out.print(String.format("Level %s :", ++currentLevel)); } } System.out.println(); } private static void printByZigZag(Node root) { if (root == null) { return; } LinkedList<Node> queue = new LinkedList<>(); queue.offerLast(root); System.out.print("Level 1 from left to right:"); int currentLevel = 1; boolean leftToRight = true; Node currentEnd = root, nextEnd = null; while (!queue.isEmpty()) { Node node; if (leftToRight) { node = queue.pollFirst(); } else { node = queue.pollLast(); } System.out.print(" " + node.val); if (leftToRight) { if (node.left != null) { queue.offerLast(node.left); nextEnd = nextEnd == null ? node.left : nextEnd; } if (node.right != null) { queue.offerLast(node.right); nextEnd = nextEnd == null ? node.right : nextEnd; } } else { if (node.right != null) { queue.offerFirst(node.right); nextEnd = nextEnd == null ? node.right : nextEnd; } if (node.left != null) { queue.offerFirst(node.left); nextEnd = nextEnd == null ? node.left : nextEnd; } } if (node == currentEnd && !queue.isEmpty()) { currentEnd = nextEnd; leftToRight = !leftToRight; nextEnd = null; System.out.println(); if (leftToRight) { System.out.print(String.format("Level %s from left to right:", ++currentLevel)); } else { System.out.print(String.format("Level %s from right to left:", ++currentLevel)); } } } System.out.println(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); Node[] nodes = new Node[n + 1]; for (int i = 1; i <= n; ++i) { nodes[i] = new Node(i); } Node root = nodes[in.nextInt()]; for (int i = 1; i <= n; ++i) { int fa = in.nextInt(); nodes[fa].left = nodes[in.nextInt()]; nodes[fa].right = nodes[in.nextInt()]; } printByLevel(root); printByZigZag(root); } } }