c++ | Preorder Traversal | Easy to understand
\n# Code\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(
\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Codec {\npublic:\n    string serialize(TreeNode* root) {\n        return encode(root);\n    }\n    TreeNode* deserialize(string data) {\n        stringstream ss(data);\n        string item;\n        TreeNode* root = NULL;\n        \n        while (getline (ss, item, \'-\')) \n            root = insert(root, stoi(item));\n\n        return root;\n    }\n    \nprivate:\n    string encode(TreeNode* root) {\n        if (!root)\n            return "";\n        return to_string(root->val) + "-" + encode(root->left)+encode(root->right);\n    }\n    \n    TreeNode* insert(TreeNode* root, int val) {\n        if (root == NULL) {\n\t\t\tTreeNode* temp=new TreeNode(val);\n\t\t\treturn temp;\n\t\t}\n    \n\t\tif (val<=root->val)\n\t\t\troot->left=insert(root->left,val);\n    \n\t\telse\n\t\t\troot->right=insert(root->right,val);\n    \n\t\treturn root;\n    }\n};\n\n// Your Codec object will be instantiated and called as such:\n// Codec* ser = new Codec();\n// Codec* deser = new Codec();\n// string tree = ser->serialize(root);\n// TreeNode* ans = deser->deserialize(tree);\n// return ans;\n```
['C++']