c++ | Preorder Traversal | Easy to understand
\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : v
```\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\n    // Encodes a tree to a single string.\n    string serialize(TreeNode* root) \n{\n   string str="";\n   fun(root,str);\n   return str;          \n}\nvoid fun(TreeNode* root,string &str)\n{\n\tif(root==NULL)\n\t{\n\t\treturn;\n\t}\n    str.append(to_string(root->val));\n    str.push_back(\'-\');\n\tfun(root->left,str);\n\tfun(root->right,str);\n    \n}\n// Decodes your encoded data to tree.\nTreeNode* deserialize(string str) \n{\n\tTreeNode* root=NULL;\n    string s="";\n    for(int i=0;i<str.length();i++)\n    {\n    \tif(str[i]==\'-\')\n    \t{\n    \t\tint num=stoi(s);\n    \t\troot=fun(root,num);\n    \t\ts.clear();\n    \t\tcontinue;\n\t\t}\n\t\telse\n\t\t{\n\t\t   s.push_back(str[i]);\t\n\t\t}\n\t}\n\treturn root;\n}\nTreeNode* fun(TreeNode* root,int &num)\n{\n\tif(root==NULL)\n\t{\n\t\treturn new TreeNode(num);\n\t}\n\tif(num > root->val)\n\t{\n\t\troot->right=fun(root->right,num);\n\t}\n\tif(num < root->val)\n\t{\n\t\troot->left=fun(root->left,num);\n\t}\n\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```
['Depth-First Search', 'Breadth-First Search', 'Binary Search Tree', 'C', 'C++']