1. 程式人生 > >【劍指offer】Java實現-序列化與反序列化二叉樹

【劍指offer】Java實現-序列化與反序列化二叉樹

題目描述

實現兩個函式,分別用來序列化和反序列化二叉樹

思路

序列化:把一棵二叉樹按照某種遍歷方式的結果以某種格式儲存為字串,從而使得記憶體中簡歷起來的二叉樹可以持久儲存 反序列化:根據某種遍歷方式得到的序列化字串結果,重構二叉樹

程式碼

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public
class Solution { //使用前序遍歷序列化二叉樹 String Serialize(TreeNode root) { StringBuffer sb=new StringBuffer(); if(root==null){ //空節點(#) sb.append("#,"); return sb.toString(); } sb.append(root.val+","); sb.append(Serialize(root.left)); sb.append(Serialize(root.right)); return
sb.toString(); } //反序列化:根據某種遍歷方式得到的序列化字串結果,重構二叉樹 int index=-1; TreeNode Deserialize(String str) { index++; int len=str.length(); if(index>=len) return null; //以逗號分隔,返回一個字串陣列 String[] str1=str.split(","); TreeNode node=null; //遍歷str1陣列,重構二叉樹:當前遍歷元素非 # 則作為一個結點插入樹中,作為上一個結點的左兒子;
//當前遍歷元素為 # 則表示此子樹已結束,遍歷下一個元素作為上一個結點的右孩子 //即遍歷到數字作為上一個結點的左孩子,遇到#變向作為上一個結點的右孩子 if(!str1[index].equals("#")){ node=new TreeNode(Integer.valueOf(str1[index])); node.left=Deserialize(str); node.right=Deserialize(str); } return node; } }

目錄