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

秋招时,华为二面被问到如何实现二叉树的序列化和反序列化。
关键点:如果节点值为空,用特殊字符【#】占位。

package scu.stone.spring;

/**
 * 华为面试:二叉树的序列化和反序列,空值用特殊值【#】占位 
 * @author fu_stone
 */

/** 二叉树如下:
 *  	   0
 *       /   \
 *      1     2
 *  	     /  \
 *          3    4
 */

public class Serializer {
	public static void main(String[] args) {
		TreeNode root = new TreeNode(0);
		TreeNode node1 = new TreeNode(1);
		TreeNode node2 = new TreeNode(2);
		TreeNode node3 = new TreeNode(3);
		TreeNode node4 = new TreeNode(4);
		
		root.left = node1;
		root.right = node2;
		node2.left = node3;
		node2.right = node4;
		
		Serializer serializer = new Serializer();
		String serializedStr = serializer.Serialize(root);
		System.out.println(serializedStr);
		TreeNode node = serializer.Deserialize(serializedStr);
		System.out.println(node);
	}
	//基于先序遍历进行序列化
    public String Serialize(TreeNode root) {
        if(root == null)
            return "";
        StringBuilder sBuilder = new StringBuilder();
        serialize_func(root, sBuilder);
        return sBuilder.toString();
    }
    public void serialize_func(TreeNode root, StringBuilder sBuilder) {
        if(root == null) {
            sBuilder.append("#,");
            return;
        }
        sBuilder.append(root.val + ",");
//        sBuilder.append(',');
        serialize_func(root.left, sBuilder); //递归
        serialize_func(root.right, sBuilder);
    }

    int index = -1;
    //反序列化
    public TreeNode Deserialize(String str) {
        if(str.length() == 0)
            return null;
        String[] strs = str.split(",");
        return deSerialize_func(strs);
    }

    public TreeNode deSerialize_func(String[] strs) {
        index++;
        if(!strs[index].equals("#")) {
            TreeNode root = new TreeNode(0);
            root.val = Integer.parseInt(strs[index]);
            root.left = deSerialize_func(strs); //递归
            root.right = deSerialize_func(strs);
            return root;
        }
        return null;
    }
}

输出结果如下:

0,1,#,#,2,3,#,#,4,#,#,
TreeNode [val=0, left=TreeNode [val=1, left=null, right=null], right=TreeNode [val=2, left=TreeNode [val=3, left=null, right=null], right=TreeNode [val=4, left=null, right=null]]]

你可能感兴趣的:(java,数据结构)