二叉樹--反序列化一棵樹

今天延續(xù)上一章的內(nèi)容,反序列化一棵樹。

題目介紹

給定一個(gè)序列化后的字符串,反序列化為一棵樹,例如:

You may deserialize the following string:
"[1,2,3,null,null,4,5]"
as
    1
   / \
  2   3
     / \
    4   5

實(shí)現(xiàn)思路

反序列化的實(shí)現(xiàn)相比序列化簡單點(diǎn),整個(gè)過程如下:
1、先將字符串去除頭尾的"["和"]",然后將字符串轉(zhuǎn)換為數(shù)組。
2、遍歷數(shù)組,從下標(biāo)為0開始,逐步生成子節(jié)點(diǎn)。

實(shí)現(xiàn)代碼

public class SolutionCodec {

   public TreeNode deserialize(String data) {
        if (data.indexOf("[") != 0 || data.indexOf("]") != data.length() - 1) {
            return null;
        }

        String[] arr = data.substring(1, data.length() - 1).split(",");
        if (arr != null && arr.length > 0) {
            return buildTreeNode(arr, 0);
        }

        return null;
    }

    private TreeNode buildTreeNode(String[] arr, int index) {
        TreeNode node = buildTreeNode(arr[index]);
        if (null != node) {
            int leftIndex = 2 * index + 1;
            if (leftIndex < arr.length) {
                node.left = buildTreeNode(arr, leftIndex);
            }
            int rIndex = 2 * (index + 1);
            if (rIndex < arr.length) {
                node.right = buildTreeNode(arr, rIndex);
            }
        }
        return node;
    }

    private TreeNode buildTreeNode(String valStr) {
        if (null == valStr || "".equals(valStr) || "null".equals(valStr)) {
            return null;
        }
        int val = Integer.valueOf(valStr);
        return new TreeNode(val);
    }
}

算法相關(guān)實(shí)現(xiàn)源碼地址:https://github.com/xiekq/rubs-algorithms

不知不覺中數(shù)據(jù)結(jié)構(gòu)相關(guān)的文章寫了差不多30篇了,突然發(fā)現(xiàn)雖然題目做了,內(nèi)容也發(fā)了,但是真正框架性的知識還沒有什么頭緒。
認(rèn)真總結(jié)思考后覺得是對相關(guān)算法知識的總結(jié)不足,同時(shí)學(xué)習(xí)的真正驅(qū)動(dòng)力不足。后續(xù)的內(nèi)容會(huì)對自己由更高的要求,輸出真正的質(zhì)量文章。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容