public static void printInOrder(Node head, int height, String to, int len) { if (head == null) { return; } printInOrder(head.right, height + 1, "v", len); String val = to + head.value + to; int lenM = val.length(); int lenL = (len - lenM) / 2; int lenR = len - lenM - lenL; val = getSpace(lenL) + val + getSpace(lenR); System.out.println(getSpace(height * len) + val); printInOrder(head.left, height + 1, "^", len); }
public static String getSpace(int num) { String space = " "; StringBuffer buf = new StringBuffer(""); for (int i = 0; i < num; i++) { buf.append(space); } return buf.toString(); }
public static void main(String[] args) { Node head = new Node(1); head.left = new Node(-222222222); head.right = new Node(3); head.left.left = new Node(Integer.MIN_VALUE); head.right.left = new Node(555555); head.right.right = new Node(66); head.left.left.right = new Node(777); printTree(head); }
// 以head为头的树,请先序列化成字符串返回 public static String serialByPre(Node head) { if (head == null) return"#_"; String res = head.value + "_"; res += serialByPre(head.left); res += serialByPre(head.right); return res; } // 反序列化 public static Node reconByPreString(String preStr) { String[] values = preStr.split("_"); Queue<String> queue = new LinkedList<String>(); for (int i = 0; i != values.length; i++) { queue.add(values[i]); } return reconPreOrder(queue); }
public static Node reconPreOrder(Queue<String> queue) { String value = queue.poll(); if (value.equals("#")) { return null; } Node head = new Node(Integer.valueOf(value)); head.left = reconPreOrder(queue); head.right = reconPreOrder(queue); returnhead; }
题目 : 对折一张纸n次打开,请打印出折痕凹凸情况 规律 :
每次对折后,在上一次的每个折痕的上下都会出现一个新的折痕,上面的是凹折痕,下面的是凸折痕
这是一颗头节点为凹折痕,每一棵左子树都是凹折痕,每一颗右子树都是凸折痕的满二叉树
1 2 3 4 5 6 7 8 9
// i是节点的层数,N一共的层数,down == true 凹 down == false 凸 public static void printProcess(int i, int N, boolean down) { if (i > N) // 超过深度直接返回 return; printProcess(i + 1, N, true); System.out.println(down ? "凹" : "凸"); printProcess(i + 1, N, false); }