2014.06.14 22:49
简介:
二叉树是学习树结构时接触的第一个概念,其他衍生的表示形式包括N叉树(随便多少叉)、二叉链表(土话也叫左孩子右兄弟)。由于单纯的二叉树是无序的,能做的事情不太多,我只实现了基本的结构体和序列化方法。
图示:
实现:
1 // My implementation for binary tree. 2 #include <string> 3 #include <vector> 4 using namespace std; 5 6 struct TreeNode { 7 int val; 8 TreeNode *left; 9 TreeNode *right; 10 TreeNode(int _val): val(_val), left(nullptr), right(nullptr) {}; 11 }; 12 13 // One of the (de)serialization method I wrote. 14 // Here is a serialization sample for this piece of code: {3,1,#,#,10,6,#,#,11,#,14,#,#} 15 // 3 16 // / \ 17 // 1 10 18 // / \ 19 // 6 11 20 // \ 21 // 14 22 class BinaryTreeSerializer { 23 public: 24 string serialize(TreeNode *root) { 25 string res = "{"; 26 27 // preorder traversal 28 serializeTraversal(root, res); 29 res[res.length() - 1] = '}'; 30 31 return res; 32 }; 33 34 TreeNode *deserialize(string s) { 35 vector<string> data; 36 int i, j, len; 37 38 len = (int)s.length(); 39 i = 1; 40 while (true) { 41 j = i + 1; 42 while (s[j] != ',' && s[j] != '}') { 43 ++j; 44 } 45 data.push_back(s.substr(i, j - i)); 46 i = j + 1; 47 if (i >= len) { 48 break; 49 } 50 } 51 52 int iter = 0; 53 TreeNode *root = nullptr; 54 55 // preorder traversal 56 deserializeTraversal(data, root, iter); 57 58 return root; 59 }; 60 private: 61 static char ss[10]; 62 63 void serializeTraversal(TreeNode *root, string &res) { 64 if (root == nullptr) { 65 res += "#,"; 66 } else { 67 sprintf(ss, "%d", root->val); 68 res += string(ss); 69 res.push_back(','); 70 serializeTraversal(root->left, res); 71 serializeTraversal(root->right, res); 72 } 73 }; 74 75 void deserializeTraversal(vector<string> &data, TreeNode *&root, int &iter) { 76 ++iter; 77 if (data[iter - 1] == "#") { 78 root = nullptr; 79 } else { 80 int val; 81 82 sscanf(data[iter - 1].c_str(), "%d", &val); 83 root = new TreeNode(val); 84 deserializeTraversal(data, root->left, iter); 85 deserializeTraversal(data, root->right, iter); 86 } 87 }; 88 }; 89 90 int main() 91 { 92 return 0; 93 }