LeetCode每日一題-二叉樹的序列化與反序列化

題目

序列化是將一個數據結構或者物件轉換為連續的位元位的操作,進而可以將轉換後的資料儲存在一個檔案或者記憶體中,同時也可以透過網路傳輸到另一個計算機環境,採取相反方式重構得到原資料。

請設計一個演算法來實現二叉樹的序列化與反序列化。這裡不限定你的序列 / 反序列化演算法執行邏輯,你只需要保證一個二叉樹可以被序列化為一個字串並且將這個字串反序列化為原始的樹結構。

示例 1:

輸入:root = [1,2,3,null,null,4,5] (見下圖)

輸出:[1,2,3,null,null,4,5]

連結:https://leetcode-cn。com/problems/serialize-and-deserialize-binary-tree

LeetCode每日一題-二叉樹的序列化與反序列化

分析

這道題是困難級別,之所以是困難,不是因為它的演算法複雜,而是如果你嚴格按照示例的格式來做,你完成它將變得很困難。

一開始我也沒想到序列化順序可以自己決定,不必像示例那樣一層一層地來,如果你不幸地被示例誤導了,那這確實是一道困難題。

跳開示例,解決這道題的思路就是怎麼方便怎麼來就是了,使用前序遍歷是比較簡單的解法。

程式碼

public class Codec { // Encodes a tree to a single string。 public String serialize(TreeNode root) { if(root == null){ return “X”; } //前序遍歷 return root。val + “,” + serialize(root。left) + “,” + serialize(root。right); } // Decodes your encoded data to tree。 public TreeNode deserialize(String data) { if(data。equals(“X”)){ return null; } String[] datas = data。split(“,”); TreeNode node = new TreeNode(Integer。parseInt(datas[0])); recursive(node, 0, datas); return node; } int recursive(TreeNode parent, int startIndex, String[] datas){ //超出陣列範圍退出 if(startIndex + 1 >= datas。length){ return startIndex; } // if(!datas[startIndex + 1]。equals(“X”)) { TreeNode node = new TreeNode(Integer。parseInt(datas[startIndex + 1])); parent。left = node; startIndex = recursive(node,startIndex + 1 ,datas ); }else { startIndex ++; } if(!datas[startIndex +1]。equals(“X”)) { TreeNode node = new TreeNode(Integer。parseInt(datas[startIndex + 1])); parent。right = node; startIndex = recursive(node,startIndex + 1 ,datas ); }else { startIndex ++; } return startIndex; }}

結果

LeetCode每日一題-二叉樹的序列化與反序列化

關注個人微信公眾號:肌肉碼農,回覆“好友”討論問題。