1. 程式人生 > 實用技巧 >劍指 Offer 37. 序列化二叉樹 (難,多個小技巧)- 8月19日

劍指 Offer 37. 序列化二叉樹 (難,多個小技巧)- 8月19日

題目

劍指 Offer 37. 序列化二叉樹

我的思路

從樹變成題目要求的字串,藉助佇列層序遍歷即可。注意整數變成字串可以用輸出運算子<<。

從一個層序遍歷的字串序列轉化為一顆二叉樹,可以考慮完全二叉樹的特性,一個節點i的孩子是2i和2i+1。

技巧:

stoi(string val)函式字串轉整數

上面的寫法,利用輸入運算子,可以連續讀取多個被空格間隔的字串。直到讀取到終止符

我的實現

題解的實現

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 
*/ class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { ostringstream out; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* tmp = q.front(); q.pop(); if (tmp) {
out<<tmp->val<<" "; q.push(tmp->left); q.push(tmp->right); } else { out<<"null "; } } return out.str(); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { istringstream input(data);
string val; vector<TreeNode*> vec; while (input >> val) { if (val == "null") { vec.push_back(NULL); } else { vec.push_back(new TreeNode(stoi(val))); } } int j = 1; // i每往後移動一位,j移動兩位,j始終是當前i的左子下標 for (int i = 0; j < vec.size(); ++i) { // 肯定是j先到達邊界,所以這裡判斷j < vec.size() if (vec[i] == NULL) continue; // vec[i]為null時跳過。 if (j < vec.size()) vec[i]->left = vec[j++]; // 當前j位置為i的左子樹 if (j < vec.size()) vec[i]->right = vec[j++]; // 當前j位置為i的右子樹 } return vec[0]; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));

拓展學習