二叉树的序列化与反序列化

二叉树节点定义

class TreeNode{
	public TreeNode(int val) {
		super();
		this.val = val;
	}
	public int val;
	public TreeNode left;
	public TreeNode right;
	public int getVal() {
		return val;
	}
	public void setVal(int val) {
		this.val = val;
	}
	public TreeNode getLeft() {
		return left;
	}
	public void setLeft(TreeNode left) {
		this.left = left;
	}
	public TreeNode getRight() {
		return right;
	}
	public void setRight(TreeNode right) {
		this.right = right;
	}

}
public class SeriableNode {
	private String deserializeStr;
	public static void main(String[] args) {
		SeriableNode sn=new SeriableNode();
		TreeNode root=new TreeNode(1);
		TreeNode root1=new TreeNode(12);
		TreeNode root2=new TreeNode(13);
		TreeNode root3=new TreeNode(121);
		TreeNode root4=new TreeNode(131);
		TreeNode root5=new TreeNode(1312);
		root.left=root1;
		root.right=root2;
		root1.left=root3;
		root2.left=root4;
		root4.right=root5;
		System.out.println(sn.Serialize(root));


	}
        /**
	*二叉树序列化方法
	*/	
	public String Serialize(TreeNode root) {
	    if (root == null)
	        return "#";
	    return root.val + " " + Serialize(root.left) + " " + Serialize(root.right);
	}

	public TreeNode Deserialize(String str) {
	    deserializeStr = str;
	    return Deserialize();
	}
	/**
	*二叉树反序列化方法
	*/
	private TreeNode Deserialize() {
	    if (deserializeStr.length() == 0)
	        return null;
	    int index = deserializeStr.indexOf(" ");
	    String node = index == -1 ? deserializeStr : deserializeStr.substring(0, index);
	    deserializeStr = index == -1 ? "" : deserializeStr.substring(index + 1);
	    if (node.equals("#"))
	        return null;
	    int val = Integer.valueOf(node);
	    TreeNode t = new TreeNode(val);
	    t.left = Deserialize();
	    t.right = Deserialize();
	    return t;
	}

}

运行结果: image.png

本站运行时间: 0天 0小时 00分00秒

Copyright © 2020 过去的,未来的

Powered by Halo • Theme by Subtle Galaxy • REFERENCE FROM 寒山

Back to the top