面试题37. 序列化二叉树
Posted ocpc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面试题37. 序列化二叉树相关的知识,希望对你有一定的参考价值。
题目:
解答:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Codec { 11 public: 12 13 // Encodes a tree to a single string. 14 string serialize(TreeNode* root) 15 { 16 string res; 17 queue<TreeNode*> q; 18 q.push(root); 19 20 while (!q.empty()) 21 { 22 auto node = q.front(); 23 if (node) 24 { 25 res += to_string(node->val) + ‘ ‘; 26 q.push(node->left); 27 q.push(node->right); 28 } 29 else 30 { 31 res += "null "; 32 } 33 q.pop(); 34 } 35 36 // cout << res; 37 return res; 38 } 39 40 // Decodes your encoded data to tree. 41 TreeNode* deserialize(string data) 42 { 43 vector<TreeNode*> list; 44 for (int l = 0, r = 0; l < data.size(); ) 45 { 46 r = l; 47 while (data[r] != ‘ ‘) 48 { 49 r ++ ; 50 } 51 if (data[l] == ‘n‘) 52 { 53 l = r + 1; 54 list.push_back(NULL); 55 continue; 56 } 57 int val = 0, sign = 1; 58 if (l < r && data[l] == ‘-‘) 59 { 60 sign = -1, l ++ ; 61 } 62 for (int i = l; i < r; i ++ ) 63 { 64 val = val * 10 + data[i] - ‘0‘; 65 } 66 val *= sign; 67 l = r + 1; 68 auto newNode = new TreeNode(val); 69 list.push_back(newNode); 70 } 71 72 auto newList = list[0]; 73 auto curNode = newList; 74 75 // j表示当前的根节点,遇到null就递进 76 // i表示当前的孩子节点,相邻两个构成一个父节点的孩子节点 77 for (int i = 1, j = 1; j < list.size() && i < list.size(); j ++ ) 78 { 79 if (!curNode) 80 { 81 curNode = list[j]; 82 continue; 83 } 84 curNode->left = list[i]; 85 curNode->right = list[i + 1]; 86 curNode = list[j]; 87 i += 2; 88 } 89 90 return newList; 91 } 92 };
以上是关于面试题37. 序列化二叉树的主要内容,如果未能解决你的问题,请参考以下文章