面試題37:序列化二叉樹

題目:請實現一個函數,分別用來序列化和反序列化二叉樹
思路:序列化的時候,用中序遍歷,注意葉子節(jié)點的左右子節(jié)點用“#”代替;反序列化的時候,也是按照中序遍歷的順序。
解決方案:

public class Question37 {
    static class BinaryTreeNode {
        int value;
        BinaryTreeNode left;
        BinaryTreeNode right;

        public BinaryTreeNode(int value) {
            this.value = value;
        }
    }
    public static String serialize(BinaryTreeNode root){
        StringBuffer sb = new StringBuffer();
        if (root == null){
            sb.append("#,");
            return sb.toString();
        }
        sb.append(root.value + ",");
        sb.append(serialize(root.left));
        sb.append(serialize(root.right));
        return sb.toString();
    }
    static int index = -1;
    public static BinaryTreeNode deSerialize(String str){
        index++;
        int len = str.length();
        if (index >= len) return null;
        String[] strArray = str.split(",");
        BinaryTreeNode node = null;
        if (!strArray[index].equals("#")){
            node = new BinaryTreeNode(Integer.valueOf(strArray[index]));
            node.left = deSerialize(str);
            node.right = deSerialize(str);
        }
        return node;
    }

    public static void main(String[] args) {
        BinaryTreeNode pHead = new BinaryTreeNode(3);
        BinaryTreeNode pAhead = new BinaryTreeNode(2);
        BinaryTreeNode pBhead = new BinaryTreeNode(5);
        BinaryTreeNode pChead = new BinaryTreeNode(7);
        BinaryTreeNode pDhead = new BinaryTreeNode(1);
        pHead.left = pAhead;
        pHead.right = pBhead;
        pBhead.left = pChead;
        pAhead.left = pDhead;

        System.out.println(serialize(pHead));
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容