二叉树
结构描述
//定义二叉树节点
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int value){
this.value = value;
}
}
二叉树遍历
public class RecursiveTraversalBT {
//定义二叉树节点
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int value){
this.value = value;
}
}
public static void f(Node head){
if (head == null){
return;
}
//1
f(head.left);
//2
f(head.right);
//3
}
//递归遍历
//先序遍历二叉树
public static void pre(Node head){
if (head == null){
return;
}
System.out.print(head.value+" ");
pre(head.left);
pre(head.right);
}
//递归、中序遍历二叉树
public static void in(Node head){
if (head == null){
return;
}
in(head.left);
System.out.print(head.value+" ");
in(head.right);
}
//递归、后序遍历二叉树
public static void pos(Node head){
if (head == null){
return;
}
pos(head.left);
pos(head.right);
System.out.print(head.value+" ");
}
public static void main(String[] args) {
Node head = new Node(1);
head.left = new Node(2);
head.right = new Node(3);
head.left.left = new Node(4);
head.left.right = new Node(5);
head.right.left = new Node(6);
head.right.right = new Node(7);
System.out.println("先序遍历;");
pre(head);
System.out.println();
System.out.println("中序遍历:");
in(head);
System.out.println();
System.out.println("后序遍历:");
pos(head);
}
}
非递归遍历
import java.util.Stack;
public class UnRecursiveTraversalBT {
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int value){
this.value = value;
}
}
//非递归先序遍历二叉树
public static void pre(Node head){
System.out.println("pre-order");
if (head != null){
Stack<Node> stack = new Stack<>();
stack.add(head);
while (!stack.isEmpty()){
head = stack.pop();
System.out.print(head.value+" ");
if (head.right != null){
stack.push(head.right);
}
if (head.left != null){
stack.push(head.left);
}
}
}
System.out.println();
}
//非递归中序遍历二叉树
public static void in(Node head){
System.out.println("in-order");
if (head != null){
Stack<Node> stack = new Stack<>();
while (!stack.isEmpty() || head != null){
if (head != null){
stack.push(head);
head = head.left;
}else {
head = stack.pop();
System.out.print(head.value+" ");
head = head.right;
}
}
}
System.out.println();
}
//非递归后序遍历二叉树
public static void pos1(Node head){
System.out.println("pso1-order");
if (head != null){
Stack<Node> stack1 = new Stack<>();
Stack<Node> stack2 = new Stack<>();
stack1.push(head);
while (!stack1.isEmpty()){
head = stack1.pop(); //根 右 左
stack2.push(head);
if (head.left!=null){
stack1.push(head.left);
}
if (head.right != null){
stack1.push(head.right);
}
}
while (!stack2.isEmpty()){
System.out.print(stack2.pop().value+" "); // 左 右 根
}
}
System.out.println();
}
public static void pos2(Node head){
System.out.println("pos2-order");
if (head != null){
Stack<Node> stack = new Stack<>();
Node c = null;
stack.push(head);
while (!stack.isEmpty()){
c = stack.peek();
if (c.left != null && head != c.left && head != c.right){
stack.push(c.left);
}else if (c.right != null && head != c.right){
stack.push(c.right);
}else {
System.out.print(stack.pop().value+" ");
head = c;
}
}
}
System.out.println();
}
public static void main(String[] args) {
Node head = new Node(1);
head.left = new Node(2);
head.right = new Node(3);
head.left.left = new Node(4);
head.left.right = new Node(5);
head.right.left = new Node(6);
head.right.right = new Node(7);
System.out.print("先序遍历:");
pre(head);
System.out.print("中序遍历:");
in(head);
System.out.print("后序遍历:");
pos1(head);
pos2(head);
}
}
层次遍历
import java.util.LinkedList;
import java.util.Queue;
public class LevelTraversalBT {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
//按二叉树的层次遍历
//用队列
public static void level(Node head){
if (head == null){
return;
}
Queue<Node> queue = new LinkedList<>();
queue.add(head);
while (!queue.isEmpty()){
Node cur = queue.poll();
System.out.print(cur.value+" ");
if (cur.left != null){
queue.add(cur.left);
}
if (cur.right != null){
queue.add(cur.right);
}
}
System.out.println();
}
public static void main(String[] args) {
Node head = new Node(1);
head.left = new Node(2);
head.right = new Node(3);
head.left.left = new Node(4);
head.left.right = new Node(5);
head.right.left = new Node(6);
head.right.right = new Node(7);
level(head);
}
}
二叉树的序列化和反序列化
例如:
([1,2,3,null,null,4,5] 对应的二叉树)
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class SerializeAndReconstructTree {
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int value){
this.value = value;
}
}
/*
* 二叉树可以通过先序、后序或者按层遍历的方式序列化和反序列化,
* 以下代码全部实现了。
* 但是,二叉树无法通过中序遍历的方式实现序列化和反序列化
* 因为不同的两棵树,可能得到同样的中序序列,即便补了空位置也可能一样。
* 比如如下两棵树
* __2
* /
* 1
* 和
* 1__
* \
* 2
* 补足空位置的中序遍历结果都是{ null, 1, null, 2, null}
*
* */
//先序序列化
public static Queue<String> preSerial(Node head){
Queue<String> ans = new LinkedList<>();
pres(head,ans);
return ans;
}
private static void pres(Node head, Queue<String> ans) {
if (head == null){
ans.add(null);
}else {
ans.add(String.valueOf(head.value));
pres(head.left,ans);
pres(head.right,ans);
}
}
//中序 序列化
public static Queue<String> inSerial(Node head){
Queue<String> ans = new LinkedList<>();
ins(head,ans);
return ans;
}
private static void ins(Node head, Queue<String> ans) {
if (head == null){
ans.add(null);
}else {
ins(head.left,ans);
ans.add(String.valueOf(head.value));
ins(head.right,ans);
}
}
//后序 序列化
public static Queue<String> posSerial(Node head){
Queue<String> ans = new LinkedList<>();
poss(head,ans);
return ans;
}
private static void poss(Node head, Queue<String> ans) {
if (head == null){
ans.add(null);
}else {
poss(head.left,ans);
poss(head.right,ans);
ans.add(String.valueOf(head.value));
}
}
//反序列化 先序
public static Node buildByPreQueue(Queue<String> preList){
if (preList == null || preList.size()==0){
return null;
}
return preb(preList);
}
private static Node preb(Queue<String> preList) {
String value = preList.poll();
if (value == null){
return null;
}
Node head = new Node(Integer.valueOf(value));
head.left = preb(preList);
head.right = preb(preList);
return head;
}
//反序列化 后序方式
public static Node buildByPosQueue(Queue<String> posList){
if (posList == null || posList.size() == 0){
return null;
}
//左右根 -> stack(根右左)
Stack<String> stack = new Stack<>();
while (!posList.isEmpty()){
stack.push(posList.poll());
}
return posb(stack);
}
private static Node posb(Stack<String> stack) {
String value = stack.pop();
if (value == null){
return null;
}
Node head = new Node(Integer.valueOf(value));
head.right = posb(stack);
head.left = posb(stack);
return head;
}
//层次遍历 序列化
public static Queue<String> levelSerial(Node head){
Queue<String> ans = new LinkedList<>();
if (head == null){
ans.add(null);
}else {
ans.add(String.valueOf(head.value));
Queue<Node> queue = new LinkedList<>();
queue.add(head);
while (!queue.isEmpty()){
head = queue.poll();
if (head.left != null){
ans.add(String.valueOf(head.left.value));
queue.add(head.left);
}else {
ans.add(null);
}
if (head.right != null){
ans.add(String.valueOf(head.right.value));
queue.add(head.right);
}else {
ans.add(null);
}
}
}
return ans;
}
//反序列化 层次遍历
public static Node buildByLevelQueue(Queue<String> levelList){
if (levelList == null || levelList.size() == 0){
return null;
}
Node head = generateNode(levelList.poll());
Queue<Node> queue = new LinkedList<>();
if (head != null){
queue.add(head);
}
Node node = null;
while (!queue.isEmpty()){
node = queue.poll();
node.left = generateNode(levelList.poll());
node.right = generateNode(levelList.poll());
if (node.left != null){
queue.add(node.left);
}
if (node.right != null){
queue.add(node.right);
}
}
return head;
}
private static Node generateNode(String poll) {
if (poll == null){
return null;
}
return new Node(Integer.valueOf(poll));
}
// for test
public static Node generateRandomBST(int maxLevel, int maxValue) {
return generate(1, maxLevel, maxValue);
}
// for test
public static Node generate(int level, int maxLevel, int maxValue) {
if (level > maxLevel || Math.random() < 0.5) {
return null;
}
Node head = new Node((int) (Math.random() * maxValue));
head.left = generate(level + 1, maxLevel, maxValue);
head.right = generate(level + 1, maxLevel, maxValue);
return head;
}
// for test
public static boolean isSameValueStructure(Node head1, Node head2) {
if (head1 == null && head2 != null) {
return false;
}
if (head1 != null && head2 == null) {
return false;
}
if (head1 == null && head2 == null) {
return true;
}
if (head1.value != head2.value) {
return false;
}
return isSameValueStructure(head1.left, head2.left) && isSameValueStructure(head1.right, head2.right);
}
// for test
public static void printTree(Node head) {
System.out.println("Binary Tree:");
printInOrder(head, 0, "H", 17);
System.out.println();
}
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) {
int maxLevel = 5;
int maxValue = 100;
int testTimes = 1000000;
System.out.println("test begin");
for (int i = 0; i < testTimes; i++) {
Node head = generateRandomBST(maxLevel, maxValue);
Queue<String> pre = preSerial(head);
Queue<String> pos = posSerial(head);
Queue<String> level = levelSerial(head);
Node preBuild = buildByPreQueue(pre);
Node posBuild = buildByPosQueue(pos);
Node levelBuild = buildByLevelQueue(level);
if (!isSameValueStructure(preBuild, posBuild) || !isSameValueStructure(posBuild, levelBuild)) {
System.out.println("Oops!");
}
}
System.out.println("test finish!");
}
}
打印一棵二叉树
public class PrintBT {
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int value){
this.value = value;
}
}
public static void printTree(Node head){
System.out.println("print Tree");
printInOrder(head,0,"H",17);
System.out.println();
}
private 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 lenL = (len - val.length()) /2;
int lenR = len - val.length() - lenL;
val = getSpace(lenL)+val+getSpace(lenR);
System.out.println(getSpace(len*height)+val);
printInOrder(head.left,height+1,"^",len);
}
private static String getSpace(int len) {
String space = " ";
StringBuffer buffer = new StringBuffer("");
for (int i = 0; i < len; i++) {
buffer.append(space);
}
return buffer.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(55555555);
head.right.right = new Node(66);
head.left.left.right = new Node(777);
printTree(head);
head = new Node(1);
head.left = new Node(2);
head.right = new Node(3);
head.left.left = new Node(4);
head.right.left = new Node(5);
head.right.right = new Node(6);
head.left.left.right = new Node(7);
printTree(head);
head = new Node(1);
head.left = new Node(1);
head.right = new Node(1);
head.left.left = new Node(1);
head.right.left = new Node(1);
head.right.right = new Node(1);
head.left.left.right = new Node(1);
printTree(head);
}
}
求二叉树最宽的层有多少个节点
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
public class TreeMaxWidth {
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int value){
this.value = value;
}
}
public static int maxWidthUseMap(Node head){
if (head == null){
return 0;
}
Queue<Node> queue = new LinkedList<>();
queue.add(head);
HashMap<Node, Integer> levelMap = new HashMap<>(); //key在那一层 value
levelMap.put(head,1);
int curLevel = 1;//当前第几层数
int curLevelNodes = 0; // 当前层数的节点数
int max = 0;
while (!queue.isEmpty()){
Node cur = queue.poll();
int curLevelNode =levelMap.get(cur);
if (cur.left != null){
queue.add(cur.left);
levelMap.put(cur.left,curLevelNode+1);
}
if (cur.right != null){
queue.add(cur.right);
levelMap.put(cur.right,curLevelNode+1);
}
if (curLevelNode == curLevel){
curLevelNodes++;
}else {
max = Math.max(max,curLevelNodes);
curLevel++;
curLevelNodes = 1;
}
}
max = Math.max(max,curLevelNodes);
return max;
}
public static int maxWidthNoMap(Node head){
if (head == null){
return 0;
}
int max = 0;
int curLevelNodes = 0; //当前层节点数
Queue<Node> queue = new LinkedList<>();
queue.add(head);
Node nodeEnd = head; //当前层最右节点
Node nextNode = null;//下一层最右节
while (!queue.isEmpty()){
Node cur = queue.poll();
if (cur.left != null){
queue.add(cur.left);
nextNode = cur.left;
}
if (cur.right != null){
queue.add(cur.right);
nextNode = cur.right;
}
curLevelNodes++;
if (cur == nodeEnd){
max = Math.max(max,curLevelNodes);
curLevelNodes = 0;
nodeEnd = nextNode;
}
}
return max;
}
// for test
public static Node generateRandomBST(int maxLevel, int maxValue) {
return generate(1, maxLevel, maxValue);
}
// for test
public static Node generate(int level, int maxLevel, int maxValue) {
if (level > maxLevel || Math.random() < 0.5) {
return null;
}
Node head = new Node((int) (Math.random() * maxValue));
head.left = generate(level + 1, maxLevel, maxValue);
head.right = generate(level + 1, maxLevel, maxValue);
return head;
}
public static void main(String[] args) {
int maxLevel = 10;
int maxValue = 100;
int testTimes = 1000000;
for (int i = 0; i < testTimes; i++) {
Node head = generateRandomBST(maxLevel, maxValue);
if (maxWidthUseMap(head) != maxWidthNoMap(head)) {
System.out.println("Oops!");
}
}
System.out.println("finish!");
}
}
补充题
package com.msb.test8;
public class PaperFolding {
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int value){
this.value = value;
}
}
//借鉴中序遍历
public static void printAllFold(int N){
process(1,N,true);
System.out.println();
}
private static void process(int i, int n, boolean down) {
if (i > n){
return;
}
process(i+1,n,true);
System.out.print(down ? "凹 ":"凸 ");
process(i+1,n,false);
}
public static void main(String[] args) {
int n = 3;
printAllFold(n);
}
}