設計算法將二叉樹序列化為字符串,並能從字符串反序列化重建原樹。格式不限,但需無狀態(不使用類成員/全局/靜態變量存狀態)。
採用 LeetCode 官方格式:層序遍歷,null 表示空節點,如 [1,2,3,null,null,4,5]。
反序列化核心難點:父子索引映射
若為完全二叉樹,父索引
i對應子索引2i+1,2i+2。但層序含null時,實際索引需扣除前序 null 數:數組: [5, 4, 7, 3, null, 2, null, -1, null, 9, ...] 索引: 0 1 2 3 4 5 6 7 8 9 節點 2 在索引 5,其左子 9 在索引 9(而非 2*5+1=11) 原因:索引 4 是 null,佔位但無子節點,導致後續索引前移 2 位規律:節點
i的左右子索引 =2*(i - nullCount[i]) + 1和+2,其中nullCount[i]為i前的 null 總數。Java 完整反序列化實現
0) nullCnt[i] = nullCnt[i-1]; if ("null".equals(vals[i])) { nodes[i] = null; nullCnt[i]++; } else { nodes[i] = new TreeNode(Integer.parseInt(vals[i])); } } for (int i = 0; i < n; ++i) { if (nodes[i] == null) continue; int leftIdx = 2 * (i - nullCnt[i]) + 1; int rightIdx = leftIdx + 1; if (leftIdx < n) nodes[i].left = nodes[leftIdx]; if (rightIdx < n) nodes[i].right = nodes[rightIdx]; } return nodes[0]; }複雜度分析