二叉树的序列化和反序列化(先序+按层)

import java.util.LinkedList;
import java.util.Queue;
public class Main444_BinaryTree_序列化And反序列化 {
	// 创建结点内部类
	public static class Node{
		public int value;
		public Node left;
		public Node right;
		public Node(int data) {
			this.value = data;
		}
	}
	// 先序遍历的序列化
	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 queue = new LinkedList();
		for(int i=0;i != values.length;i++) {
			queue.offer(values[i]);
		}
		return reconPreOrder(queue);
	}
	private static Node reconPreOrder(Queue 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);
		return head;
	}
	// 按层遍历的序列化
	public static String serialByLevel(Node head) {
		if(head == null) {
			return "#,";
		}
		String res = head.value+"!";
		Queue queue = new LinkedList();
		queue.offer(head);
		while(!queue.isEmpty()) {
			head = queue.poll();
			if(head.left!=null) {
				res+=head.left.value+",";
				queue.offer(head.left);
			}else {
				res+="#,";
			}
			if(head.right != null) {
				res += head.right.value + ",";
				queue.offer(head.right);
			}else {
				res+="#,";
			}
		}
		return res;
	}
	// 按层反序列化
	public static Node reconByLevelString(String leveStr) {
		String[] values = leveStr.split(",");
		int index = 0;
		Node head = generateNodeByString(values[index++]);
		Queue queue = new LinkedList();
		if(head != null) {
			queue.offer(head);
		}
		Node node = null;
		while(!queue.isEmpty()) {
			node = queue.poll();
			node.left = generateNodeByString(values[index++]);
			node.right = generateNodeByString(values[index++]);
			if(node.left != null) {
				queue.offer(node.left);
			}
			if(node.right != null) {
				queue.offer(node.right);
			}
		}
		return head;
	}
	private static Node generateNodeByString(String val) {
		if(val.equals("#")) {
			return null;
		}
		return new Node(Integer.valueOf(val));
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	}
}

 

你可能感兴趣的:(Tree)