question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
longest-substring-of-all-vowels-in-order | Easy C++ Soln || Sliding Window | easy-c-soln-sliding-window-by-mitedyna-cotw | \nclass Solution {\npublic:\n int longestBeautifulSubstring(string w) {\n unordered_map<char,int> mp;\n unordered_map<int,int> cnt;\n mp | mitedyna | NORMAL | 2021-05-26T18:59:47.408043+00:00 | 2021-05-26T18:59:47.408077+00:00 | 236 | false | ```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string w) {\n unordered_map<char,int> mp;\n unordered_map<int,int> cnt;\n mp[\'a\']=0;mp[\'e\']=1;mp[\'i\']=2;mp[\'o\']=3;mp[\'u\']=4;\n int i=0,j=0,n=w.length(),ans=0;\n while(i<n){\n int x=mp[w[i]];\n for(int k=x+1;k<5;k++){\n while(j<n && cnt.count(k) && cnt[k]>0){\n cnt[mp[w[j]]]--;\n if(cnt[mp[w[j]]]==0)cnt.erase(mp[w[j]]);\n j++;\n }\n }\n cnt[x]++;\n if(cnt.size()==5)ans=max(ans,i-j+1);\n i++;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C', 'Sliding Window'] | 0 |
longest-substring-of-all-vowels-in-order | Faster than 93% of C# submissions | Inline comments | O(N) time | faster-than-93-of-c-submissions-inline-c-0bz9 | \npublic class Solution {\n public int LongestBeautifulSubstring(string str) {\n int max = 0, s = 0;\n char last = \'$\';\n\t\t// Store vowel s | abhishek-ks | NORMAL | 2021-05-18T08:36:07.801562+00:00 | 2021-05-18T10:21:28.997802+00:00 | 70 | false | ```\npublic class Solution {\n public int LongestBeautifulSubstring(string str) {\n int max = 0, s = 0;\n char last = \'$\';\n\t\t// Store vowel sequence\n var map = new Dictionary<char, int>() {\n {\'a\',0}, {\'e\',1},{\'i\',2},{\'o\',3},{\'u\',4}\n };\n for(int i=0;i<str.Length;i++)\n {\n if(last==\'$\') //No beautiful string in getting processed\n {\n if(str[i]!=\'a\') continue; //beautiful string starts with \'a\'\n s = i; // mark the start index, used later for calculating length\n while(i<str.Length-1 && str[i+1]==\'a\') {\n i++; \n }\n last = \'a\';\n }\n else {\n char cur = str[i];\n if((map[last]+1)!=map[cur]) { // not in sequence\n if(cur==\'a\') i--; // if it is \'a\', it can be a beautiful string, so consider it again\n last = \'$\';\n s = 0;\n continue;\n }\n else if((map[last]+1)==map[str[i]]) {\n while(i<str.Length-1 && str[i+1]==cur) {\n i++; \n }\n if(cur==\'u\') { // Last char of a beautiful string, find the length\n max = Math.Max(max,i-s+1);\n\t\t\t\t\t\t // re-initialize for next beautiful strings, if any:\n last = \'$\';\n s = 0;\n }\n else last = cur;\n }\n }\n }\n return max;\n }\n}\n```\nPlease upvote if it helps! | 1 | 0 | [] | 0 |
longest-substring-of-all-vowels-in-order | c++ - O(n) time and O(1) space, beats 93% | with comments | c-on-time-and-o1-space-beats-93-with-com-93uu | \nclass Solution {\npublic:\n // concept used is sliding window.\n // O(n) time complexity and O(1) space complexity.\n int longestBeautifulSubstring(s | subhajitadhikary | NORMAL | 2021-05-07T15:12:07.590975+00:00 | 2021-05-07T15:14:54.959797+00:00 | 284 | false | ```\nclass Solution {\npublic:\n // concept used is sliding window.\n // O(n) time complexity and O(1) space complexity.\n int longestBeautifulSubstring(string word) {\n int maxlen=0; // this will store the max length of valid substring\n int start=0,end=0; // the pointers to traverse the sliding window\n int n=word.size();\n \n while(end<n && word[end]!=\'a\')\n end++; // starting from the point where first occurence of \'a\' is there\n \n start=end;\n int prev=0; // this will traverse the vowels vector \n vector<char>vowels{\'a\',\'e\',\'i\',\'o\',\'u\'};\n \n while(end<n)\n {\n \n if(word[end]>=vowels[prev])\n {\n if(prev==4) // prev==4 means we have reached the end of vowels, and now we should update the maxlen if possible.\n maxlen=max(maxlen,end-start+1);\n else if(word[end]==vowels[prev+1]) // this tells us that vowels have come in order i.e \'a\' then \'e\' then \'i\' then \'o\' and then \'u\', so there is no harm in incrementing prev. \n {\n prev++;\n if(prev==4)\n maxlen=max(maxlen,end-start+1);\n }\n else if(word[end]>vowels[prev+1]) // this situation is not good for us as the consecutive order of vowels have broken, so we have to reset everything and make start and end to the position where the next \'a\' occurs, if it is there.\n {\n prev=0;\n while(end<n && word[end]!=\'a\')\n {\n end++;\n }\n start=end;\n end--;\n }\n }\n \n else // this is also the situation where the consecutive order breaks, so again reset\n {\n prev=0;\n while(end<n && word[end]!=\'a\')\n end++;\n start=end;\n end--;\n }\n \n end++;\n }\n return maxlen;\n }\n};\n``` | 1 | 0 | ['Two Pointers', 'C', 'Sliding Window', 'C++'] | 0 |
longest-substring-of-all-vowels-in-order | Golang simple solution | golang-simple-solution-by-tjucoder-o155 | go\nfunc longestBeautifulSubstring(word string) int {\n lbs := 0\n level := 0\n current := 0\n for _, c := range word {\n switch c {\n | tjucoder | NORMAL | 2021-05-04T18:56:17.809660+00:00 | 2021-05-04T18:56:17.809706+00:00 | 90 | false | ```go\nfunc longestBeautifulSubstring(word string) int {\n lbs := 0\n level := 0\n current := 0\n for _, c := range word {\n switch c {\n case \'a\':\n if level == 1 {\n current++\n } else {\n level = 1\n current = 1\n }\n case \'e\':\n if level == 2 {\n current++\n } else if level == 1 {\n level = 2\n current++\n } else {\n level = 0\n current = 0\n }\n case \'i\':\n if level == 3 {\n current++\n } else if level == 2 {\n level = 3\n current++\n } else {\n level = 0\n current = 0\n }\n case \'o\':\n if level == 4 {\n current++\n } else if level == 3 {\n level = 4\n current++\n } else {\n level = 0\n current = 0\n }\n case \'u\':\n if level == 5 {\n current++\n } else if level == 4 {\n level = 5\n current++\n } else {\n level = 0\n current = 0\n }\n if current > lbs {\n lbs = current\n }\n }\n }\n return lbs\n}\n``` | 1 | 0 | ['Go'] | 0 |
longest-substring-of-all-vowels-in-order | C++ Simple | Easy To Understand | c-simple-easy-to-understand-by-rudraksh2-isyi | \nclass Solution {\npublic:\n int longestBeautifulSubstring(string str) {\n \tint a = str.length();\n\tint vowel = 0;\n\tint r = 0;\n\tint maxi = 0;\n | fakeramsingh | NORMAL | 2021-05-03T09:34:03.424263+00:00 | 2021-05-03T09:34:03.424292+00:00 | 93 | false | ```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string str) {\n \tint a = str.length();\n\tint vowel = 0;\n\tint r = 0;\n\tint maxi = 0;\n\tchar last = \'a\';\n\tfor (int i = 0; i < a; i++) {\n\t\tif (str[i] == \'a\') {\n\t\t\tr = i;\n vowel++;\n\t\t\tbreak;\n\t\t}\n\t}\n if (vowel==0)return 0;\n\tfor (int x = r + 1; x < a; x++) {\n\t\tif (str[x] >= last) {\n\t\t\tif (str[x] != last)\n\t\t\t\tvowel++;\n\t\t\tlast = str[x];\n\t\t}\n\t\telse {\n\t\t\tvowel = 1;\n\t\t\tr = x;\n\t\t\tlast = str[x];\n\t\t}\n\t\tif (vowel >= 5) {\n\t\t\tmaxi = max(maxi, x - r + 1);\n\t\t}\n\t}\nreturn maxi;\n }\n};\n``` | 1 | 1 | [] | 0 |
longest-substring-of-all-vowels-in-order | Python | Clean Code | python-clean-code-by-morningstar317-yb13 | ```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n i = 0\n j = 0\n n = len(word)\n maxVal = 0\n | morningstar317 | NORMAL | 2021-04-29T05:47:19.509564+00:00 | 2021-04-29T05:47:19.509603+00:00 | 93 | false | ```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n i = 0\n j = 0\n n = len(word)\n maxVal = 0\n res = set()\n while j < n:\n k = j\n while k < n and word[k]==word[j]:\n res.add(word[k])\n k+=1\n \n if len(res)==5:\n maxVal = max(maxVal,k-i)\n \n if k<n and word[k] < word[j]:\n res = set()\n \n i = k\n \n j = k\n return maxVal\n \n\t\t | 1 | 0 | [] | 0 |
longest-substring-of-all-vowels-in-order | [Java] O(N) sliding window | 18ms | java-on-sliding-window-18ms-by-travis031-gj5i | \nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int maxLen = 0;\n for (int i = 0; i < word.length();) {\n | travis0315 | NORMAL | 2021-04-27T05:06:04.344164+00:00 | 2021-04-27T05:06:04.344223+00:00 | 104 | false | ```\nclass Solution {\n public int longestBeautifulSubstring(String word) {\n int maxLen = 0;\n for (int i = 0; i < word.length();) {\n int start = i, cnt = 1, cur = word.charAt(i);\n while (i < word.length() && cur <= word.charAt(i)) {\n if (cur < word.charAt(i)) {\n cur = word.charAt(i);\n ++cnt;\n }\n ++i;\n }\n if (cnt == 5) {\n maxLen = Math.max(i - start, maxLen);\n }\n }\n return maxLen;\n }\n}\n``` | 1 | 0 | ['Sliding Window', 'Java'] | 0 |
longest-substring-of-all-vowels-in-order | javascript | javascript-by-mukundjha-p2rx | \nhere i used sliding window approach\n\ni will use two pointers slow and fast.\nstack to keep track of last encountered vowel.\nand also a set to keep watch if | mukundjha | NORMAL | 2021-04-26T16:47:25.794273+00:00 | 2021-04-26T16:47:25.794309+00:00 | 296 | false | ```\nhere i used sliding window approach\n\ni will use two pointers slow and fast.\nstack to keep track of last encountered vowel.\nand also a set to keep watch if set has all 5 vowels(which means we have a valid window)\nmap each vowel in increamenting order.\n\nnow start moving fast pointer\n\nthere are 3 things possilbe.\n\n1st \nstack is empty so just add given vowel\n\n2nd\nthe new char which fast pointer is pointing is wether equal or has more value than vowel on top of stack than just add \nvowel to both stack and set\ncheck if set has all 5 vowels and calculate maxlength.\n\n3rd\nwe have now encountered a vowel which has less value than top of stack which means we hit our window \nso move slow pointer to fast and also decrease fast bcz lets say in this given ex. \'a e i o u a a a i\'\n when fast pointer is at 5th index on line 66 fast pointer will get incremented and hence index 5 will not get processed and won\'t be added to stack and set. \nagain check wether set has all 5 vowls or not and cal. maxlength. and clear both stack and set.\n\n(sorry for my poor english and upvote if found helpful or downvote if felt confusing :) )\n\nvar longestBeautifulSubstring = function(word) {\n let maxLength = 0;\n let stack = [];\n let map = new Map();\n let set = new Set();\n let slow = 0,\n fast = 0;\n\n\n map.set("a", 1);\n map.set("e", 2);\n map.set("i", 3);\n map.set("o", 4);\n map.set("u", 5);\n\n\n while (fast < word.length) {\n\n let char = word[fast];\n if (stack.length === 0) {\n\n stack.push(char);\n set.add(char);\n\n } else if (map.get(char) >= map.get(stack[stack.length - 1])) {\n\n stack.push(char);\n set.add(char);\n if (set.size === 5) {\n maxLength = Math.max(maxLength, fast - slow + 1);\n\n }\n } else {\n\n slow = fast;\n fast--; \n\n if (set.size === 5) {\n maxLength = Math.max(maxLength, fast - slow + 1);\n }\n\n stack = [];\n set.clear();\n\n }\n\n fast++;\n\n }\n return maxLength;\n};\n\n``` | 1 | 0 | ['Sliding Window', 'JavaScript'] | 0 |
longest-substring-of-all-vowels-in-order | C# Easy Sliding Window | c-easy-sliding-window-by-venki07-fc7v | \npublic class Solution {\n public int LongestBeautifulSubstring(string word) {\n \n var set = new HashSet<char>();\n int start = 0; | venki07 | NORMAL | 2021-04-25T22:15:18.828292+00:00 | 2021-04-25T22:15:18.828325+00:00 | 43 | false | ```\npublic class Solution {\n public int LongestBeautifulSubstring(string word) {\n \n var set = new HashSet<char>();\n int start = 0; \n int max = 0;\n \n for(int end = 0; end < word.Length; end++)\n {\n if(end > 0 && word[end] < word[end -1])\n {\n set.Clear(); \n start = end;\n }\n set.Add(word[end]); \n if(set.Count == 5)\n max = Math.Max(max, end - start + 1); \n }\n return max;\n }\n}\n``` | 1 | 0 | [] | 1 |
longest-substring-of-all-vowels-in-order | [Python3] Simple One Pass Greedy Solution | python3-simple-one-pass-greedy-solution-tha4a | \nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n vowels = {\'a\' : 0, \'e\' : 1, \'i\' : 2, \'o\' : 3, \'u\' : 4}\n | blackspinner | NORMAL | 2021-04-25T19:07:02.311911+00:00 | 2021-04-25T19:07:02.311946+00:00 | 30 | false | ```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n vowels = {\'a\' : 0, \'e\' : 1, \'i\' : 2, \'o\' : 3, \'u\' : 4}\n n = len(word)\n last = \'#\'\n j = 0\n res = 0\n for i in range(n):\n if word[i] in vowels:\n if last == \'#\' and word[i] == \'a\':\n j = i\n last = \'a\'\n elif last != \'#\' and (vowels[last] == vowels[word[i]] or vowels[last] + 1 == vowels[word[i]]):\n last = word[i]\n elif last != \'#\':\n j = i\n if word[i] == \'a\':\n last = \'a\'\n else:\n last = \'#\'\n if last == \'u\':\n res = max(res, i - j + 1)\n return res\n``` | 1 | 0 | [] | 0 |
longest-substring-of-all-vowels-in-order | TLE || simple ans using regex | tle-simple-ans-using-regex-by-kondekarsh-3ipb | This solution exceeds time\n\nplease suggest me where it goes wrong\n\n\nimport re\nclass Solution:\n def longestBeautifulSubstring(self, word):\n dat | kondekarshubham123 | NORMAL | 2021-04-25T07:35:57.603811+00:00 | 2021-04-25T07:42:07.085118+00:00 | 41 | false | This solution exceeds time\n\nplease suggest me where it goes wrong\n\n```\nimport re\nclass Solution:\n def longestBeautifulSubstring(self, word):\n data = re.findall(\'[a]+[e]+[i]+[o]+[u]+\',word)\n return max(map(len,data)) if data else 0\n``` | 1 | 0 | ['Python3'] | 0 |
longest-substring-of-all-vowels-in-order | Very Simple and Descriptive C++ code | very-simple-and-descriptive-c-code-by-te-vidt | \nclass Solution {\npublic:\n int longestBeautifulSubstring(string s) {\n int n=s.size();\n map<char,int> mp { {\'a\',0},{\'e\',1}, {\'i\',2}, { | tejpratapp468 | NORMAL | 2021-04-25T06:49:34.969463+00:00 | 2021-04-25T06:49:34.969505+00:00 | 53 | false | ```\nclass Solution {\npublic:\n int longestBeautifulSubstring(string s) {\n int n=s.size();\n map<char,int> mp { {\'a\',0},{\'e\',1}, {\'i\',2}, {\'o\',3}, {\'u\',4} };\n int ans=0,cnt=0;\n vector<int> v(5,0);v[mp[s[0]]]++,cnt++;\n for(int i=1;i<n;i++)\n {\n if(mp[s[i]]>=mp[s[i-1]]){\n cnt++;v[mp[s[i]]]++;\n }\n else {\n bool ok=1;\n for(int i=0;i<5;i++)\n {\n if(v[i]==0) {\n ok=0;break;\n }\n }\n if(ok) ans=max(ans,cnt);\n for(int i=0;i<5;i++) v[i]=0;\n cnt=1;v[mp[s[i]]]++;\n }\n }\n if(cnt)\n {\n bool ok=1;\n for(int i=0;i<5;i++)\n {\n if(v[i]==0) {\n ok=0;break;\n }\n }\n if(ok) ans=max(ans,cnt);\n }\n return ans;\n }\n}; \n``` | 1 | 0 | [] | 0 |
longest-substring-of-all-vowels-in-order | javascript sliding window 100ms | javascript-sliding-window-100ms-by-henry-kfzq | \nconst mx = Math.max;\nconst t = \'aeiou\';\nconst longestBeautifulSubstring = (s) => {\n let n = s.length;\n let res = 0;\n for (let i = 0; i < n; i+ | henrychen222 | NORMAL | 2021-04-25T05:31:39.062240+00:00 | 2021-04-25T05:38:31.030333+00:00 | 375 | false | ```\nconst mx = Math.max;\nconst t = \'aeiou\';\nconst longestBeautifulSubstring = (s) => {\n let n = s.length;\n let res = 0;\n for (let i = 0; i < n; i++) {\n if (s[i] == \'a\') { // if want the longest, so have to keep as much as "a" comes left of "eiou", so the answer should start with "a"\n let right = i;\n let flag = 1;\n for (let j = 0; j < 5; j++) {\n if (s[right] != t[j]) {\n flag = 0;\n break;\n }\n while (right < n && s[right] == t[j]) right++;\n }\n if (flag) res = mx(res, right - i);\n i = right - 1;\n }\n }\n return res;\n};\n``` | 1 | 0 | ['Sliding Window', 'JavaScript'] | 0 |
serialize-and-deserialize-bst | the General Solution for Serialize and Deserialize BST and Serialize and Deserialize BT | the-general-solution-for-serialize-and-d-0rp1 | BST\nuse upper and lower boundaries to check whether we should add null\njava\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * i | greatlim | NORMAL | 2018-10-04T20:28:05.849722+00:00 | 2018-10-17T07:25:29.308896+00:00 | 46,597 | false | ### BST\nuse upper and lower boundaries to check whether we should add `null`\n```java\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n StringBuilder sb = new StringBuilder();\n serialize(root, sb);\n return sb.toString();\n }\n \n public void serialize(TreeNode root, StringBuilder sb) {\n if (root == null) return;\n sb.append(root.val).append(",");\n serialize(root.left, sb);\n serialize(root.right, sb);\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n if (data.isEmpty()) return null;\n Queue<String> q = new LinkedList<>(Arrays.asList(data.split(",")));\n return deserialize(q, Integer.MIN_VALUE, Integer.MAX_VALUE);\n }\n \n public TreeNode deserialize(Queue<String> q, int lower, int upper) {\n if (q.isEmpty()) return null;\n String s = q.peek();\n int val = Integer.parseInt(s);\n if (val < lower || val > upper) return null;\n q.poll();\n TreeNode root = new TreeNode(val);\n root.left = deserialize(q, lower, val);\n root.right = deserialize(q, val, upper);\n return root;\n }\n}\n\n// Your Codec object will be instantiated and called as such:\n// Codec codec = new Codec();\n// codec.deserialize(codec.serialize(root));\n```\n\n### Binary Tree\nuse `#` whether we should add `null`\n```java\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n StringBuilder sb = new StringBuilder();\n serialize(root, sb);\n return sb.toString();\n }\n \n public void serialize(TreeNode root, StringBuilder sb) {\n if (root == null) {\n sb.append("#").append(",");\n } else {\n sb.append(root.val).append(",");\n serialize(root.left, sb);\n serialize(root.right, sb);\n }\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n Queue<String> q = new LinkedList<>(Arrays.asList(data.split(",")));\n return deserialize(q);\n }\n \n public TreeNode deserialize(Queue<String> q) {\n String s = q.poll();\n if (s.equals("#")) return null;\n TreeNode root = new TreeNode(Integer.parseInt(s));\n root.left = deserialize(q);\n root.right = deserialize(q);\n return root;\n }\n \n}\n\n// Your Codec object will be instantiated and called as such:\n// Codec codec = new Codec();\n// codec.deserialize(codec.serialize(root));\n```\n\n | 501 | 0 | [] | 37 |
serialize-and-deserialize-bst | Python O( N ) solution. easy to understand | python-o-n-solution-easy-to-understand-b-bdrh | EDIT: Thanks to @WKVictor , this solution uses 'deque' instead of 'list' as queue. And the performance is O( N )\n\n\nclass Codec:\n\n def serialize(self, ro | leetcodeftw | NORMAL | 2016-11-05T16:15:34.918000+00:00 | 2018-10-26T15:26:53.018142+00:00 | 18,547 | false | EDIT: Thanks to @WKVictor , this solution uses 'deque' instead of 'list' as queue. And the performance is O( N )\n\n```\nclass Codec:\n\n def serialize(self, root):\n vals = []\n\n def preOrder(node):\n if node:\n vals.append(node.val)\n preOrder(node.left)\n preOrder(node.right)\n\n preOrder(root)\n\n return ' '.join(map(str, vals))\n\n # O( N ) since each val run build once\n def deserialize(self, data):\n vals = collections.deque(int(val) for val in data.split())\n\n def build(minVal, maxVal):\n if vals and minVal < vals[0] < maxVal:\n val = vals.popleft()\n node = TreeNode(val)\n node.left = build(minVal, val)\n node.right = build(val, maxVal)\n return node\n\n return build(float('-infinity'), float('infinity'))\n\n``` | 160 | 0 | [] | 15 |
serialize-and-deserialize-bst | Java PreOrder + Queue solution | java-preorder-queue-solution-by-magicshi-5jsh | Hi all, I think my solution is pretty straightforward and easy to understand, not that efficient though. And the serialized tree is compact.\nPre order traversa | magicshine | NORMAL | 2016-11-06T22:39:03.499000+00:00 | 2018-10-21T01:01:25.603021+00:00 | 68,390 | false | Hi all, I think my solution is pretty straightforward and easy to understand, not that efficient though. And the serialized tree is compact.\nPre order traversal of BST will output root node first, then left children, then right.\n```\nroot left1 left2 leftX right1 rightX\n```\nIf we look at the value of the pre-order traversal we get this:\n```\nrootValue (<rootValue) (<rootValue) (<rootValue) |separate line| (>rootValue) (>rootValue)\n```\nBecause of BST's property: before the |separate line| all the node values are **less than root value**, all the node values after |separate line| are **greater than root value**. We will utilize this to build left and right tree.\n\nPre-order traversal is BST's serialized string. I am doing it iteratively.\nTo deserialized it, use a queue to recursively get root node, left subtree and right subtree.\n\n\nI think time complexity is O(NlogN).\nErrr, my bad, as @ray050899 put below, worst case complexity should be O(N^2), when the tree is really unbalanced. \n\n\nMy implementation\n```\npublic class Codec {\n private static final String SEP = ",";\n private static final String NULL = "null";\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n StringBuilder sb = new StringBuilder();\n if (root == null) return NULL;\n //traverse it recursively if you want to, I am doing it iteratively here\n Stack<TreeNode> st = new Stack<>();\n st.push(root);\n while (!st.empty()) {\n root = st.pop();\n sb.append(root.val).append(SEP);\n if (root.right != null) st.push(root.right);\n if (root.left != null) st.push(root.left);\n }\n return sb.toString();\n }\n\n // Decodes your encoded data to tree.\n // pre-order traversal\n public TreeNode deserialize(String data) {\n if (data.equals(NULL)) return null;\n String[] strs = data.split(SEP);\n Queue<Integer> q = new LinkedList<>();\n for (String e : strs) {\n q.offer(Integer.parseInt(e));\n }\n return getNode(q);\n }\n \n // some notes:\n // 5\n // 3 6\n // 2 7\n private TreeNode getNode(Queue<Integer> q) { //q: 5,3,2,6,7\n if (q.isEmpty()) return null;\n TreeNode root = new TreeNode(q.poll());//root (5)\n Queue<Integer> samllerQueue = new LinkedList<>();\n while (!q.isEmpty() && q.peek() < root.val) {\n samllerQueue.offer(q.poll());\n }\n //smallerQueue : 3,2 storing elements smaller than 5 (root)\n root.left = getNode(samllerQueue);\n //q: 6,7 storing elements bigger than 5 (root)\n root.right = getNode(q);\n return root;\n }\n}\n``` | 154 | 7 | [] | 41 |
serialize-and-deserialize-bst | Concise C++ 19ms solution beating 99.4% | concise-c-19ms-solution-beating-994-by-c-b5ml | Sharing my solution which doesn't have to parse string for comma at all!\n\nThe encoding schema is preorder of BST, and to decode this we can use the same preor | code9yitati | NORMAL | 2017-02-19T07:06:38.673000+00:00 | 2018-10-24T04:46:45.509883+00:00 | 25,414 | false | Sharing my solution which doesn't have to parse string for comma at all!\n\nThe encoding schema is preorder of BST, and to decode this we can use the same preorder traversal to do it in one pass with recursion in O(n) time.\n\nTo minimize the memory, I used binary format instead of ascii format for each integer, just burn those int into 4 chars will save you a lot!!!\n\nReally if using ASCII numbers you are paying a lot of penalty memory for integers over 4 digit long and parsing comma is just as painful.\n\n```\nclass Codec {\npublic:\n\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n string order;\n inorderDFS(root, order);\n return order;\n }\n \n inline void inorderDFS(TreeNode* root, string& order) {\n if (!root) return;\n char buf[4];\n memcpy(buf, &(root->val), sizeof(int)); //burn the int into 4 chars\n for (int i=0; i<4; i++) order.push_back(buf[i]);\n inorderDFS(root->left, order);\n inorderDFS(root->right, order);\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n int pos = 0;\n return reconstruct(data, pos, INT_MIN, INT_MAX);\n }\n \n inline TreeNode* reconstruct(const string& buffer, int& pos, int minValue, int maxValue) {\n if (pos >= buffer.size()) return NULL; //using pos to check whether buffer ends is better than using char* directly.\n \n int value;\n memcpy(&value, &buffer[pos], sizeof(int));\n if (value < minValue || value > maxValue) return NULL;\n \n TreeNode* node = new TreeNode(value);\n pos += sizeof(int);\n node->left = reconstruct(buffer, pos, minValue, value);\n node->right = reconstruct(buffer, pos, value, maxValue);\n return node;\n }\n};\n``` | 141 | 4 | [] | 28 |
serialize-and-deserialize-bst | C++ simple and clean PreOrder traversal solution | c-simple-and-clean-preorder-traversal-so-zqvz | \nclass Codec {\npublic:\n\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n return encode(root);\n }\n\n // Dec | yehudisk | NORMAL | 2020-10-09T11:03:26.240085+00:00 | 2020-10-09T11:03:26.240130+00:00 | 7,811 | false | ```\nclass Codec {\npublic:\n\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n return encode(root);\n }\n\n // Decodes your encoded data to tree.\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**Like it? please upvote...** | 92 | 5 | ['C'] | 9 |
serialize-and-deserialize-bst | Deserialize from preorder and computed inorder, reusing old solution | deserialize-from-preorder-and-computed-i-m2pk | I serialize the tree's values in preorder. For deserializing, I additionally compute inorder simply by sorting the preorder. And then I just use the buildTree f | stefanpochmann | NORMAL | 2016-11-04T14:35:12.575000+00:00 | 2018-10-17T05:58:02.054287+00:00 | 30,980 | false | I serialize the tree's values in preorder. For deserializing, I additionally compute inorder simply by sorting the preorder. And then I just use the `buildTree` function that I copied&pasted from [my old solution](https://discuss.leetcode.com/topic/16221/simple-o-n-without-map) for the old problem [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/).\n```\nclass Codec:\n\n def serialize(self, root):\n def preorder(node):\n if node:\n vals.append(str(node.val))\n preorder(node.left)\n preorder(node.right)\n vals = []\n preorder(root)\n return ' '.join(vals)\n\n def deserialize(self, data):\n preorder = map(int, data.split())\n inorder = sorted(preorder)\n return self.buildTree(preorder, inorder)\n\n def buildTree(self, preorder, inorder):\n def build(stop):\n if inorder and inorder[-1] != stop:\n root = TreeNode(preorder.pop())\n root.left = build(root.val)\n inorder.pop()\n root.right = build(stop)\n return root\n preorder.reverse()\n inorder.reverse()\n return build(None)\n```\n(I had seen @shallpion's [title](https://discuss.leetcode.com/topic/65773/construct-bst-using-preorder-traversal) saying "preorder" before thinking about this problem, so can't be sure I would've had the idea myself, though I think I would've.) | 78 | 2 | [] | 22 |
serialize-and-deserialize-bst | BT & BST C++ Solution: Preorder, Comma seperated with comments | bt-bst-c-solution-preorder-comma-seperat-hera | (1) Binary Search Tree\n\nclass Codec {\npublic:\n void serializehelper(TreeNode* root, string& s){\n if(root==nullptr) return;\n \n s+= | ankurharitosh | NORMAL | 2020-03-24T10:49:28.839828+00:00 | 2020-08-28T14:00:44.307811+00:00 | 5,308 | false | (1) Binary Search Tree\n```\nclass Codec {\npublic:\n void serializehelper(TreeNode* root, string& s){\n if(root==nullptr) return;\n \n s+=to_string(root->val) + ","; // \',\' for seperating each value\n serializehelper(root->left, s);\n serializehelper(root->right, s);\n }\n \n string serialize(TreeNode* root) {\n if(root==nullptr) return "";\n \n string s="";\n serializehelper(root, s);\n \n return s;\n }\n \n int convertStringtoInt(string& data, int& pos){ // Find \',\' and return value\n pos=data.find(\',\');\n int value=stoi(data.substr(0, pos));\n return value;\n }\n \n TreeNode* deserializehelper(string& data, int min, int max) {\n if(data.size()==0) return nullptr; // If no more elements, return nullptr\n \n int pos=0;\n int value = convertStringtoInt(data, pos); // Find new value and position of \',\'\n if (value < min || value > max) return nullptr; // Is new value in given range\n \n TreeNode* tnode = new TreeNode(value); \n data=data.substr(pos+1); // Update only when in range\n \n tnode->left=deserializehelper(data, min, tnode->val); // Branch off to left & right subtree with given ranges\n tnode->right=deserializehelper(data, tnode->val, max);\n return tnode;\n }\n \n TreeNode* deserialize(string data) {\n if(data=="") return nullptr;\n return deserializehelper(data, INT_MIN, INT_MAX);\n }\n};\n```\n\n(2) Binary Tree\n```\nclass Codec {\npublic:\n string serialize(TreeNode* root) {\n if(root==nullptr) return "X";\n \n return to_string(root->val) + "," + serialize(root->left) + "," + serialize(root->right); // to_string\n }\n int convertStringtoInt(string& data){\n int pos=data.find(\',\');\n int value=stoi(data.substr(0, pos));\n data=data.substr(pos+1);\n return value;\n }\n TreeNode* deserializehelper(string& data) { // data is updated, hence by reference\n if(data[0]==\'X\'){\n if(data.size()>1)\n data=data.substr(2); // keep removing data \n return nullptr;\n }\n \n TreeNode* tnode = new TreeNode(convertStringtoInt(data)); // covert data using stoi\n tnode->left=deserializehelper(data);\n tnode->right=deserializehelper(data);\n return tnode;\n }\n TreeNode* deserialize(string data) {\n return deserializehelper(data);\n }\n};\n```\nI appreciate your upvote !! | 45 | 0 | ['Binary Search Tree', 'C', 'C++'] | 4 |
serialize-and-deserialize-bst | Using lower bound and upper bound to deserialize BST | using-lower-bound-and-upper-bound-to-des-pvh6 | The idea is to encode every non null root value by preorder traversal \n\nwhen deserializing the tree, we can pass by the lower bound and upper bound to know th | cccrrryyy | NORMAL | 2016-11-06T01:24:15.100000+00:00 | 2018-10-24T05:09:51.472616+00:00 | 14,830 | false | The idea is to encode every non null root value by preorder traversal \n\nwhen deserializing the tree, we can pass by the lower bound and upper bound to know the boundary of a subtree.\n\nThis approach has an overhead of looking up one extra number, which would be O ( 2N )\n\n```\n // Encodes a tree to a single string.\n void serialize(TreeNode* root, ostringstream& out )\n {\n if ( !root ) return;\n out << root->val << ",";\n serialize(root->left, out);\n serialize(root->right, out);\n }\n \n string serialize(TreeNode* root) {\n ostringstream ss;\n serialize(root, ss);\n return ss.str();\n }\n\n TreeNode* deserialize(const string& s, int lower, int upper, int & pos )\n {\n // pos is a variable to record the end of decoded buffer \n if ( pos == s.size() ) return nullptr;\n int cur_pos = pos;\n int number = 0;\n while( s[cur_pos] != ',')\n {\n number = number * 10 + s[cur_pos] - '0';\n ++cur_pos;\n }\n ++cur_pos;\n // The next number is not part of current subtree, should return nullptr\n if ( number < lower || number > upper ) return nullptr;\n\n TreeNode* root = new TreeNode( number );\n pos = cur_pos; // update pos \n root->left = deserialize( s, lower, root->val, pos );\n root->right = deserialize( s, root->val, upper, pos );\n return root;\n }\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n int pos = 0;\n return deserialize( data, INT_MIN, INT_MAX, pos );\n \n }\n``` | 29 | 1 | [] | 9 |
serialize-and-deserialize-bst | Java concise Solution. | java-concise-solution-by-yizeliu-auqz | \npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n if(root == null){\n return | yizeliu | NORMAL | 2018-08-29T08:00:13.037983+00:00 | 2018-10-25T03:00:31.303029+00:00 | 3,720 | false | ```\npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n if(root == null){\n return "#";\n }\n return String.valueOf(root.val) + "," + serialize(root.left) + "," + serialize(root.right);\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n String[]strs = data.split(",");\n return deserialize(strs, new int[]{0});\n }\n private TreeNode deserialize(String[]arr, int[]idx){\n if(arr[idx[0]].equals("#")){\n idx[0]++;\n return null;\n }\n TreeNode root = new TreeNode(Integer.parseInt(arr[idx[0]++]));\n root.left = deserialize(arr, idx);\n root.right = deserialize(arr, idx);\n return root;\n }\n}\n``` | 28 | 1 | [] | 6 |
serialize-and-deserialize-bst | [Python] O(n) solution, using preorder traversal, explained | python-on-solution-using-preorder-traver-6aj5 | My idea to solve this problem is to use Problem 1008. Construct Binary Search Tree from Preorder Traversal. So:\n\n1. For our serialization we just get preorder | dbabichev | NORMAL | 2020-10-09T10:17:38.550108+00:00 | 2020-10-09T10:28:28.908874+00:00 | 2,248 | false | My idea to solve this problem is to use **Problem 1008**. Construct Binary Search Tree from Preorder Traversal. So:\n\n1. For our serialization we just get preorder traversel (iterative or recursion, whatever you want, I used iterative, using stack).\n2. For deserialization we use solution with `O(n)` time complexity: we give the function two bounds - `up` and `down`: the maximum number it will handle. The left recursion will take the elements smaller than `node.val` and the right recursion will take the remaining elements smaller than `bound`.\n\n**Complexity**: both for serialization and deserialization is `O(n)`, because `self.index` will be increased by one on each iteration.\n\n```\nclass Codec:\n def serialize(self, root):\n if not root: return ""\n stack, out = [root], []\n while stack:\n cur = stack.pop()\n out.append(cur.val)\n for child in filter(None, [cur.right, cur.left]):\n stack += [child]\n \n return \' \'.join(map(str, out))\n \n def deserialize(self, data):\n preorder = [int(i) for i in data.split()]\n def helper(down, up):\n if self.idx >= len(preorder): return None\n if not down <= preorder[self.idx] <= up: return None\n root = TreeNode(preorder[self.idx])\n self.idx += 1\n root.left = helper(down, root.val)\n root.right = helper(root.val, up)\n return root\n \n self.idx = 0\n return helper(-float("inf"), float("inf"))\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 26 | 0 | [] | 2 |
serialize-and-deserialize-bst | Python, BFS > 90% | python-bfs-90-by-warmr0bot-nqdb | \nclass Codec:\n\n def serialize(self, root: TreeNode) -> str:\n """Encodes a tree to a single string.\n """\n if not root: return \'\'\ | warmr0bot | NORMAL | 2020-10-09T09:41:15.658203+00:00 | 2020-10-09T09:41:15.658247+00:00 | 2,938 | false | ```\nclass Codec:\n\n def serialize(self, root: TreeNode) -> str:\n """Encodes a tree to a single string.\n """\n if not root: return \'\'\n tree = []\n queue = deque([root])\n while queue:\n node = queue.popleft()\n if node:\n tree.append(str(node.val))\n queue.extend([node.left, node.right])\n else:\n tree.append(\'*\')\n return \',\'.join(tree)\n \n\n def deserialize(self, data: str) -> TreeNode:\n """Decodes your encoded data to tree.\n """\n if not data: return None\n tree = deque(data.split(\',\'))\n root = TreeNode(int(tree.popleft()))\n queue = deque([root])\n while queue:\n node = queue.popleft()\n \n if (left := tree.popleft()) != \'*\':\n node.left = TreeNode(int(left))\n queue.append(node.left)\n \n if (right := tree.popleft()) != \'*\':\n node.right = TreeNode(int(right))\n queue.append(node.right)\n \n return root\n``` | 24 | 0 | ['Breadth-First Search', 'Python', 'Python3'] | 3 |
serialize-and-deserialize-bst | Python O(n) sol by pre-order traversal. 75%+ [ With explanation ] | python-on-sol-by-pre-order-traversal-75-d5l3r | Python O(n) sol by pre-order traversal.\n\n---\n\nHint:\n1. Pre-order traversal of binary search tree is unique and only. (i.e., no repetition between two diffe | brianchiang_tw | NORMAL | 2020-02-08T12:40:12.271633+00:00 | 2020-02-10T05:49:40.924891+00:00 | 1,855 | false | Python O(n) sol by pre-order traversal.\n\n---\n\nHint:\n1. Pre-order traversal of binary search tree is **unique and only**. (i.e., no repetition between two different BSTs)\n\n2. **Pre-order traversal rule** of binary search tree is ( **current node, left-child, right-child**)\n\n3. Left child value < current node value < Right child value **if all elements are unique**.\n\n---\n\nAlgorithm:\n\nSerialization: \nGenerate a string to represent the input BST with preorder traversal.\n\nDeseialization:\nDecode the serialization string to rebuild BST by preorder traversal.\n\n---\n\nExample illustration\n\n---\n\nSerialization:\n\n\n\n---\n\nDeserialization:\n\n\n\n---\n\n```\nfrom collections import deque\nclass Codec:\n\n def serialize(self, root: TreeNode) -> str:\n """Encodes a tree to a single string.\n """\n \n # record of preorder traversal path\n path_of_preorder = []\n \n # Generate pre-order traversal path of binary search tree\n def helper( node ):\n \n if node:\n path_of_preorder.append( node.val )\n helper( node.left )\n helper( node.right )\n \n # ---------------------------------------------\n helper( root )\n # output as string, each node is separated by \'#\'\n return \'#\'.join( map(str, path_of_preorder) )\n \n \n \n\n def deserialize(self, data: str) -> TreeNode:\n """Decodes your encoded data to tree.\n """\n if not data:\n # corner case handle for empty tree\n return None\n \n # convert input string into doubly linked list of integer type, each node is separated by \'#\'\n node_values = deque( int(value) for value in data.split(\'#\') )\n \n # Reconstruct binary search tree by pre-order traversal\n def helper( lower_bound, upper_bound):\n \n if node_values and lower_bound < node_values[0] < upper_bound:\n \n root_value = node_values.popleft()\n root_node = TreeNode( root_value )\n \n root_node.left = helper( lower_bound, root_value )\n root_node.right = helper( root_value, upper_bound )\n \n return root_node\n \n # ---------------------------------------------\n \n return helper( float(\'-inf\'), float(\'inf\')) \n```\n\n---\n\nRelative leetcode challenge:\n[Leetcode #1008 Construct Binary Search Tree from Preorder Traversal](https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/)\n\n[Leetcode #144 Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | 24 | 1 | ['String', 'Python'] | 2 |
serialize-and-deserialize-bst | pre or post order with only keeping one bound(beat 98% and 95%) | pre-or-post-order-with-only-keeping-one-peby3 | the post-order:\n\n'''\n\npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n if (root == n | ruby71 | NORMAL | 2017-08-01T17:52:07.450000+00:00 | 2018-10-19T22:23:44.947870+00:00 | 4,339 | false | the post-order:\n\n'''\n\npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n if (root == null) {\n return null;\n }\n StringBuilder sb = new StringBuilder();\n serialize(root, sb);\n return sb.toString();\n }\n \n private void serialize(TreeNode root, StringBuilder sb) {\n if (root == null) {\n return;\n }\n serialize(root.left, sb);\n serialize(root.right, sb);\n sb.append(Integer.valueOf(root.val)).append(" ");\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n if (data == null || data.length() == 0) {\n return null;\n }\n String[] nodes = data.split(" ");\n int[] index = new int[] {nodes.length - 1};\n return deserialize(nodes, index, Integer.MIN_VALUE);\n }\n \n private TreeNode deserialize(String[] nodes, int[] index, int min) {\n if (index[0] < 0 || Integer.valueOf(nodes[index[0]]) <= min) {\n return null;\n }\n TreeNode root = new TreeNode(Integer.valueOf(nodes[index[0]--]));\n root.right = deserialize(nodes, index, root.val);\n root.left = deserialize(nodes, index, min);\n return root;\n }\n}\n\n'''\n\npre-order\n\n'''\npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n if (root == null) {\n return null;\n }\n StringBuilder sb = new StringBuilder();\n serialize(root, sb);\n return sb.toString();\n }\n \n private void serialize(TreeNode root, StringBuilder sb) {\n if (root == null) {\n return;\n }\n sb.append(root.val).append(" ");\n serialize(root.left, sb);\n serialize(root.right, sb);\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n if (data == null || data.length() == 0) {\n return null;\n }\n String[] nodes = data.split(" ");\n int[] index = new int[] {0};\n return deserialize(nodes, index, Integer.MAX_VALUE);\n }\n \n private TreeNode deserialize(String[] nodes, int[] index, int max) {\n if (index[0] >= nodes.length || Integer.valueOf(nodes[index[0]]) >= max) {\n return null;\n }\n TreeNode root = new TreeNode(Integer.valueOf(nodes[index[0]++]));\n root.left = deserialize(nodes, index, root.val);\n root.right = deserialize(nodes, index, max);\n return root;\n }\n}\n\n''' | 24 | 0 | [] | 8 |
serialize-and-deserialize-bst | Java O(n) recursive DFS without "null" Changed from Serialize and Deserialize BT | java-on-recursive-dfs-without-null-chang-9y5t | Thanks to this post, I realize that I can make use of lower and upper bound.\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode | youshan | NORMAL | 2016-11-08T00:30:43.825000+00:00 | 2018-09-16T19:37:01.148225+00:00 | 8,371 | false | Thanks to [this post](https://discuss.leetcode.com/topic/66495/using-lower-bound-and-upper-bound-to-deserialize-bst), I realize that I can make use of lower and upper bound.\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) { // preorder\n StringBuilder sb = new StringBuilder();\n serializedfs(root, sb);\n return sb.toString();\n }\n \n private void serializedfs(TreeNode root, StringBuilder sb){\n if(root == null) return; // no "null "\n sb.append(root.val).append(" ");\n serializedfs(root.left, sb);\n serializedfs(root.right, sb);\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n if(data.length() == 0) return null;\n String[] list = data.split(" ");\n TreeNode dummy = new TreeNode(0);\n deserializedfs(list, 0, dummy, true, Integer.MIN_VALUE, Integer.MAX_VALUE);\n return dummy.left;\n }\n \n private int deserializedfs(String[] list, int pos, TreeNode par, boolean isleft, \n int lower, int upper){\n if(pos >= list.length) return pos;\n \n int val = Integer.valueOf(list[pos]);\n if(val < lower || val > upper) return pos-1; // have not used this pos, so minus one\n TreeNode cur = new TreeNode(val);\n \n if(isleft) par.left = cur;\n else par.right = cur;\n\n pos = deserializedfs(list, ++pos, cur, true, lower, val);\n pos = deserializedfs(list, ++pos, cur, false, val, upper);\n return pos;\n } | 22 | 1 | [] | 2 |
serialize-and-deserialize-bst | Easy To Understand C++ Solution Using PreOrder Traversal and iostringstream | easy-to-understand-c-solution-using-preo-p517 | Because of BST, so we can use PreOrder Traversal to rebuild the tree, so do with serialize and deserialize. After using iostringstream, we can easily get the va | haoyuanliu | NORMAL | 2017-01-12T02:55:24.698000+00:00 | 2018-10-19T20:49:29.653345+00:00 | 2,778 | false | Because of BST, so we can use `PreOrder Traversal` to rebuild the tree, so do with serialize and deserialize. After using `iostringstream`, we can easily get the values and build the tree.\n\n```\nclass Codec \n{\npublic:\n\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) \n {\n ostringstream out;\n mySerialize(root, out);\n return out.str();\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) \n {\n if(data == "") return NULL;\n istringstream in(data);\n return myDeserialize(in);\n }\nprivate:\n\tvoid mySerialize(TreeNode* root, ostringstream &out)\n\t{\n\t\tif(root == NULL) return;\n\t\tout << root->val << " ";\n\t\tmySerialize(root->left, out);\n\t\tmySerialize(root->right, out);\n\t}\n\n\tTreeNode* myDeserialize(istringstream &in)\n\t{\n\t\tstring val;\n\t\tin >> val;\n\t\tTreeNode *root = new TreeNode(stoi(val));\n\t\twhile(in >> val)\n\t\t\tbuildTree(root, stoi(val));\n\t\treturn root;\n\t}\n\n\tvoid buildTree(TreeNode* root, int n)\n\t{\n\t\tif(root->val > n)\n\t\t{\n\t\t\tif(root->left == NULL)\n\t\t\t\troot->left = new TreeNode(n);\n\t\t\telse\n\t\t\t\tbuildTree(root->left, n);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(root->right == NULL)\n\t\t\t\troot->right = new TreeNode(n);\n\t\t\telse\n\t\t\t\tbuildTree(root->right, n);\n\t\t}\n\t}\n};\n``` | 18 | 0 | [] | 5 |
serialize-and-deserialize-bst | Python solution | python-solution-by-zitaowang-1g8d | One can use the encoding and decoding scheme in 297. Serialize and Deserialize Binary Tree. However, it does not use the properties of a BST: The left (right) s | zitaowang | NORMAL | 2019-01-01T01:03:27.795811+00:00 | 2019-01-01T01:03:27.795864+00:00 | 1,598 | false | One can use the encoding and decoding scheme in 297. Serialize and Deserialize Binary Tree. However, it does not use the properties of a BST: The left (right) subtree of a node contains only nodes with keys smaller (greater) than the node\'s key. Therefore, the encoding strings there does not satisfy the requirement that it should be as compact as possible. In particular, the null nodes need to be specified in the encoding string, and is redundant here. With the aforementioned BST property, one can actually recover a BST from its preorder traversal alone (without specifying the null nodes), assuming that the node values are distinct.\n\nAs a concrete example, suppose the preorder traversal of some BST gives `s = "5,4,2,3,7,9,10"`. Since the preorder traversal traverses the tree in the order `root -> left subtree -> right subtree`, we know that `"5"` must be the value of the `root` of the BST. Furthermore, by the BST property, all values smaller (larger) than `5` should be all values of nodes from the left (right) subtree. Hence, we we just need to iterate over `s[1:]` and find the first occurence (at index `i`) of some number larger than `5`. Then the left subtree would consists of values `s[1:i]` (`["4","2","3"]` in this example), and the right subtree would consists of values `s[i:]` (`["7","9","10"]` in this example). Calling the deserialize method recursively on `s[1:i]`, and `s[i:]` gives us the roots of the left subtree `l` and right subtree `r` respectively. And by assigning `root.left = l`, and `root.right = r`, and returning `root`, we finish the deserialization procedure.\n\nTime complexity for `serialize`: `O(n)`. Time complexity for `deserialize`: `O(n^2)`. Space complexity for both `serialize` and `deserialize`: `O(n)`.\n\n\n```\nclass Codec:\n\n def serialize(self, root):\n """Encodes a tree to a single string.\n \n :type root: TreeNode\n :rtype: str\n """\n def dfs(root):\n if not root:\n return \n res.append(str(root.val) + ",")\n dfs(root.left)\n dfs(root.right)\n \n res = []\n dfs(root)\n return "".join(res)\n\n def deserialize(self, data):\n """Decodes your encoded data to tree.\n \n :type data: str\n :rtype: TreeNode\n """\n def helper(arr, i, j):\n if i > j:\n return\n if i == j:\n node = TreeNode(arr[i])\n return node\n for k in range(i+1, j+1):\n if arr[k] > arr[i]:\n l = helper(arr, i+1, k-1)\n r = helper(arr, k, j)\n root = TreeNode(arr[i])\n root.left = l\n root.right = r\n return root\n l = helper(arr, i+1, j)\n root = TreeNode(arr[i])\n root.left = l\n return root\n \n arr = data.split(",")\n arr.pop()\n data = [int(x) for x in arr]\n return helper(data, 0, len(data)-1)\n```\n\nA better solution with `O(n)` iterative deserialization:\n\n```\nclass Codec:\n\n def serialize(self, root):\n """Encodes a tree to a single string.\n \n :type root: TreeNode\n :rtype: str\n """\n def dfs(root):\n if not root:\n return \n res.append(str(root.val) + ",")\n dfs(root.left)\n dfs(root.right)\n \n res = []\n dfs(root)\n return "".join(res)\n\n def deserialize(self, data):\n """Decodes your encoded data to tree.\n \n :type data: str\n :rtype: TreeNode\n """\n lst = data.split(",")\n lst.pop()\n stack = []\n head = None\n for n in lst:\n n = int(n)\n if not head:\n head = TreeNode(n)\n stack.append(head)\n else:\n node = TreeNode(n)\n if n < stack[-1].val:\n stack[-1].left = node\n else:\n while stack and stack[-1].val < n: \n u = stack.pop()\n u.right = node\n stack.append(node)\n return head\n``` | 16 | 0 | [] | 5 |
serialize-and-deserialize-bst | C++ Super Simple, Clean & Short Soluion only 11 lines! | c-super-simple-clean-short-soluion-only-j6n2c | \nclass Codec {\npublic:\n\n string serialize(TreeNode* root) \n {\n return !root ? " null" : " " + to_string(root->val) + serialize(root->left) + | debbiealter | NORMAL | 2020-10-09T08:52:43.290140+00:00 | 2020-10-09T09:26:31.363958+00:00 | 1,233 | false | ```\nclass Codec {\npublic:\n\n string serialize(TreeNode* root) \n {\n return !root ? " null" : " " + to_string(root->val) + serialize(root->left) + serialize(root->right);\n }\n\t\n TreeNode* deserialize(string data) \n {\n istringstream ss(data);\n\t\treturn buildBST(ss);\n }\n \nprivate:\n \n TreeNode* buildBST(istringstream& ss)\n {\n string s;\n ss >> s;\n \n if (s == "null")\n\t\t\treturn NULL;\n \n TreeNode* node = new TreeNode(stoi(s));\n node->left = buildBST(ss);\n node->right = buildBST(ss);\n \n return node;\n }\n};\n``` | 13 | 3 | ['C'] | 1 |
serialize-and-deserialize-bst | Easy Java Solution || 2 Approaches Beats 100% online submissions | easy-java-solution-2-approaches-beats-10-8goc | Approach\n1. Perform DFS and store the result in a string seperated by \',\' and null is represented by \'x\'\n2. To helpdeserialize follow the approach to buil | Viraj_Patil_092 | NORMAL | 2023-03-18T17:22:31.899513+00:00 | 2023-03-18T17:22:55.174906+00:00 | 2,143 | false | # Approach\n1. **Perform DFS and store the result in a string seperated by \',\' and null is represented by \'x\'**\n2. **To helpdeserialize follow the approach to build a Tree**\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N) \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Codec {\n\n public String serialize(TreeNode root) {\n StringBuilder res = new StringBuilder();\n\n helpserialize(root,res);\n\n return res.toString();\n }\n\n private void helpserialize(TreeNode root, StringBuilder res){\n if(root == null){\n res.append("x,");\n return ;\n }\n\n res.append(root.val);\n res.append(\',\');\n\n helpserialize(root.left, res);\n helpserialize(root.right, res);\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n Deque<String> q = new LinkedList<>();\n\n q.addAll(Arrays.asList(data.split(",")));\n\n return helpdeserialize(q);\n }\n\n private TreeNode helpdeserialize(Deque<String> q){\n String res = q.remove();\n\n if(res.equals("x")){\n return null;\n }\n\n TreeNode root = new TreeNode(Integer.parseInt(res));\n\n root.left = helpdeserialize(q);\n root.right = helpdeserialize(q);\n\n return root;\n }\n}\n```\n\n# Java O(1) Code\n\n# I mean... why not \uD83D\uDE02\n```\npublic class Codec {\n\n static TreeNode res;\n public String serialize(TreeNode root) {\n res = root;\n return "";\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n return res;\n }\n}\n``` | 12 | 0 | ['Tree', 'Depth-First Search', 'Binary Search Tree', 'Binary Tree', 'Java'] | 4 |
serialize-and-deserialize-bst | Small and Simple Code in C++ with O(N) time complexity | small-and-simple-code-in-c-with-on-time-p5ya6 | Do the dry run to understand\nexample:\n1 ( 2 (4) (5) ) (3 (6) ( 7 (8) (9) ) )\n1 -> children 2 and 3\n2 -> children 4 and 5\n3 -> children 6 and 7\n7 -> childr | brickcommander | NORMAL | 2022-03-05T13:41:14.794491+00:00 | 2022-10-05T11:35:53.368706+00:00 | 1,346 | false | Do the dry run to understand\nexample:\n1 ( 2 (4) (5) ) (3 (6) ( 7 (8) (9) ) )\n1 -> children 2 and 3\n2 -> children 4 and 5\n3 -> children 6 and 7\n7 -> children 8 and 9\n```\nclass Codec {\npublic:\n\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n string str = "";\n if(root == NULL) return str;\n str = to_string(root->val) + "(" + serialize(root->left) + ")" + "(" + serialize(root->right) + ")";\n return str;\n }\n\n // Decodes your encoded data to tree.\n TreeNode* decode(string &data, int &i) {\n if(i < data.size() && data[i] == \'(\') i++;\n if(i>=data.size() || data[i] == \')\') {\n return NULL;\n }\n \n int num = 0;\n while(data[i] <= \'9\' && data[i] >= \'0\') {\n num = num * 10 + (data[i] - \'0\');\n i++;\n }\n \n TreeNode* root = new TreeNode(num);\n root->left = decode(data, i);\n i++;\n root->right = decode(data, i);\n i++;\n \n return root;\n }\n \n TreeNode* deserialize(string data) {\n int i=0;\n return decode(data, i); \n }\n};\n``` | 12 | 0 | ['Depth-First Search', 'Binary Search Tree', 'Recursion', 'C', 'C++'] | 4 |
serialize-and-deserialize-bst | [Python] PreOrder Traversal - Clean & Concise - O(N) | python-preorder-traversal-clean-concise-by6of | Same with problem: 297. Serialize and Deserialize Binary Tree\n\npython\nclass Codec:\n def serialize(self, root):\n if root == None:\n ret | hiepit | NORMAL | 2020-10-09T07:32:23.104395+00:00 | 2020-10-09T08:43:05.466969+00:00 | 761 | false | Same with problem: [297. Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/)\n\n```python\nclass Codec:\n def serialize(self, root):\n if root == None:\n return "$"\n return str(root.val) + "," + self.serialize(root.left) + "," + self.serialize(root.right)\n\n def deserialize(self, data):\n nodes = data.split(",")\n self.i = 0\n def dfs():\n if self.i == len(nodes) or nodes[self.i] == "$":\n self.i += 1\n return None\n root = TreeNode(int(nodes[self.i]))\n self.i += 1\n root.left = dfs()\n root.right = dfs()\n return root\n \n return dfs()\n```\n**Complexity**\n- Time & Space: `O(N)`, where `N` is number of nodes in BST. | 12 | 1 | [] | 1 |
serialize-and-deserialize-bst | Extremely Elegant and Simple JavaScript solution | extremely-elegant-and-simple-javascript-fkepd | My serialized list takes the form of: \n[root, <elements smaller than root>, <elements bigger than root>] and this is true recursively. I cheated a little bit b | yangshun | NORMAL | 2017-06-22T15:20:21.162000+00:00 | 2017-06-22T15:20:21.162000+00:00 | 916 | false | My serialized list takes the form of: \n`[root, <elements smaller than root>, <elements bigger than root>]` and this is true recursively. I cheated a little bit by using `JSON.stringify` and `JSON.parse` but the general idea is there.\n\n```\nvar serialize = function(root) {\n function traverse(node) {\n if (!node) {\n return [];\n }\n return [node.val].concat(traverse(node.left), traverse(node.right));\n }\n return JSON.stringify(traverse(root));\n};\n\nvar deserialize = function(data) {\n function construct(arr) {\n if (!arr.length) {\n return null;\n }\n const root = new TreeNode(arr[0]);\n root.left = construct(arr.filter(num => num < root.val));\n root.right = construct(arr.filter(num => num > root.val));\n return root;\n }\n return construct(JSON.parse(data));\n};\n``` | 11 | 2 | [] | 0 |
serialize-and-deserialize-bst | simple javascript solution | simple-javascript-solution-by-osdevisnot-o6fj | \nlet serialize = (root, result = []) => {\n if (root) {\n result.push(root.val);\n result.push(...serialize(root.left));\n result.push(...serialize(r | osdevisnot | NORMAL | 2020-05-01T00:20:14.139975+00:00 | 2020-05-01T00:20:14.140011+00:00 | 979 | false | ```\nlet serialize = (root, result = []) => {\n if (root) {\n result.push(root.val);\n result.push(...serialize(root.left));\n result.push(...serialize(root.right));\n } else {\n result.push(null);\n }\n return result;\n};\n\nlet deserialize = (data) => {\n let val = data.shift();\n if (val == null) return null;\n let node = new TreeNode(val);\n node.left = deserialize(data);\n node.right = deserialize(data);\n return node;\n};\n```\n\nSee more @ https://github.com/osdevisnot/leetcode | 9 | 1 | ['JavaScript'] | 3 |
serialize-and-deserialize-bst | C++ Level-Order Serialization | c-level-order-serialization-by-votrubac-ckn2 | We can use a queue serialize the tree level-by-level. If a child node is null, we just add a separator (instead of null or something to save space).\n\nFor exam | votrubac | NORMAL | 2020-03-20T08:44:48.727114+00:00 | 2020-03-20T08:50:13.654217+00:00 | 697 | false | We can use a queue serialize the tree level-by-level. If a child node is null, we just add a separator (instead of `null` or something to save space).\n\nFor example, this tree `[5,1,7,null,3,6,8,2,null,null]` will be serialized as `5,1,7,,3,6,8,2`.\n\n```cpp\nstring serialize(TreeNode* root) {\n string res;\n vector<TreeNode*> q{root};\n while (!q.empty()) {\n vector<TreeNode*> q1;\n for (auto n : q) {\n res += (n == nullptr ? "" : to_string(n->val)) + ",";\n if (n != nullptr) {\n q1.push_back(n->left);\n q1.push_back(n->right); \n }\n }\n swap(q, q1);\n }\n while (!res.empty() && res.back() == \',\')\n res.pop_back();\n return res;\n}\nTreeNode* readNode(string& data, int &i) {\n string val;\n while (i < data.size() && data[i] != \',\')\n val += data[i++];\n ++i;\n return val.empty() ? nullptr : new TreeNode(stoi(val));\n}\nTreeNode* deserialize(string data) {\n TreeNode tmp;\n data = "," + data;\n vector<TreeNode*> q{&tmp};\n int i = 0;\n while (!q.empty()) {\n vector<TreeNode*> q1;\n for (auto n : q) {\n if (n != nullptr) {\n q1.push_back(n->left = readNode(data, i));\n q1.push_back(n->right = readNode(data, i)); \n }\n }\n swap(q, q1);\n }\n return tmp.right;\n}\n``` | 9 | 1 | [] | 0 |
serialize-and-deserialize-bst | Serialize and Deserialize BST | Python | serialize-and-deserialize-bst-python-by-utgy5 | \ndef serialize(self, root: TreeNode) -> str:\n vals = []\n\n def preOrder(node):\n if node:\n vals.append(node.val)\n | status201 | NORMAL | 2020-10-09T12:46:33.923881+00:00 | 2020-10-09T12:46:33.924018+00:00 | 466 | false | ```\ndef serialize(self, root: TreeNode) -> str:\n vals = []\n\n def preOrder(node):\n if node:\n vals.append(node.val)\n preOrder(node.left)\n preOrder(node.right)\n\n preOrder(root)\n\n return \' \'.join(map(str, vals))\n \n \n \n\n def deserialize(self, data: str) -> TreeNode:\n vals = collections.deque(int(val) for val in data.split())\n\n def build(minVal, maxVal):\n if vals and minVal < vals[0] < maxVal:\n val = vals.popleft()\n node = TreeNode(val)\n node.left = build(minVal, val)\n node.right = build(val,maxVal)\n return node\n\n return build(float(\'-inf\'), float(\'inf\'))\n\n``` | 8 | 0 | [] | 2 |
serialize-and-deserialize-bst | Python Preorder + Deque Solution. Beats 98% | python-preorder-deque-solution-beats-98-p9c30 | ```\n\tdef serialize(self, root):\n if not root:\n return "X,"\n return str(root.val) + "," + self.serialize(root.left) + self.serializ | probuddho | NORMAL | 2019-11-12T02:38:27.456135+00:00 | 2019-11-12T02:38:27.456173+00:00 | 392 | false | ```\n\tdef serialize(self, root):\n if not root:\n return "X,"\n return str(root.val) + "," + self.serialize(root.left) + self.serialize(root.right)\n\n def deserialize(self, data):\n queue = collections.deque(data.split(\',\'))\n return self.deserializeHelper(queue)\n \n def deserializeHelper(self, queue):\n if queue:\n node = queue.popleft()\n if node == \'X\':\n return None\n new_node = TreeNode(node)\n new_node.left = self.deserializeHelper(queue)\n new_node.right = self.deserializeHelper(queue)\n return new_node | 8 | 0 | [] | 2 |
serialize-and-deserialize-bst | Two Approaches || 20ms easy || 0ms object oriented | two-approaches-20ms-easy-0ms-object-orie-t02l | Solution 1:\n\npublic class Codec { // 20ms solution\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n if(root== | Lil_ToeTurtle | NORMAL | 2022-08-11T15:42:10.261379+00:00 | 2022-08-11T15:45:20.117708+00:00 | 2,035 | false | Solution 1:\n```\npublic class Codec { // 20ms solution\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n if(root==null)return "#";\n return root.val+" "+serialize(root.left)+" "+serialize(root.right);\n }\n\n // Decodes your encoded data to tree.\n String[] arr;int index;\n public TreeNode deserialize(String data) {\n arr=data.split(" ");\n index=0;\n return go();\n }\n \n private TreeNode go() {\n int index=this.index++;\n if(arr[index].equals("#")) return null;\n TreeNode root = new TreeNode(Integer.valueOf(arr[index]));\n root.left=go();\n root.right=go();\n return root;\n }\n}\n```\n\nSolution 2:\n```\npublic class Codec { // 0ms solution\n static TreeNode node;\n public String serialize(TreeNode root) {\n node = root;\n return "";\n }\n public TreeNode deserialize(String data) {\n return node;\n }\n}\n\n``` | 7 | 0 | ['Java'] | 4 |
serialize-and-deserialize-bst | Using Preorder traversal | using-preorder-traversal-by-18praneeth-rery | \nclass Codec:\n\n def serialize(self, root: TreeNode) -> str:\n res = []\n \n def dfs(root):\n if not root:\n | 18praneeth | NORMAL | 2021-08-22T19:18:33.377209+00:00 | 2021-08-22T19:18:33.377254+00:00 | 547 | false | ```\nclass Codec:\n\n def serialize(self, root: TreeNode) -> str:\n res = []\n \n def dfs(root):\n if not root:\n res.append(\'N\')\n return\n \n res.append(str(root.val))\n dfs(root.left)\n dfs(root.right)\n \n dfs(root)\n return \',\'.join(res)\n \n\n def deserialize(self, data: str) -> TreeNode:\n vals = data.split(\',\')\n self.i = 0\n \n def dfs():\n if vals[self.i] == \'N\':\n self.i += 1\n return None\n \n node = TreeNode(int(vals[self.i]))\n self.i += 1\n node.left = dfs()\n node.right = dfs()\n \n return node\n \n return dfs()\n``` | 7 | 0 | ['Depth-First Search', 'Python'] | 2 |
serialize-and-deserialize-bst | Serialize and Deserialize BST | Java | Preorder Traversal | serialize-and-deserialize-bst-java-preor-l5fo | ```\n\npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n \n if(root==null) return | niharikajha | NORMAL | 2020-10-10T03:24:29.603739+00:00 | 2020-10-10T03:24:29.603772+00:00 | 559 | false | ```\n\npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n \n if(root==null) return "";\n \n List<String> data = new ArrayList<>();\n preorderTraversal(root, data);\n \n return String.join(",", data);\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n \n if(data.length()==0) return null;\n \n String[] nodes= data.split(",");\n \n return convertPreorderTree( nodes, 0, nodes.length-1);\n }\n \n private void preorderTraversal(TreeNode root, List<String> data){\n \n if(root==null) return;\n \n data.add(""+root.val);\n \n preorderTraversal(root.left, data);\n preorderTraversal(root.right, data);\n }\n \n private TreeNode convertPreorderTree(String[] preorder, int start, int end){\n \n if(start > end) return null;\n \n TreeNode node= new TreeNode(Integer.parseInt(preorder[start]));\n \n int i= start+1;\n while(i<=end && Integer.parseInt(preorder[i]) < Integer.parseInt(preorder[start])){\n i++;\n }\n \n node.left = convertPreorderTree(preorder, start+1, i-1);\n node.right = convertPreorderTree(preorder, i, end);\n \n return node;\n }\n}\n\n | 7 | 0 | [] | 0 |
serialize-and-deserialize-bst | [C++] BFS-based Solution Explained,~99% Time, ~5% Memory | c-bfs-based-solution-explained99-time-5-ciztv | I have to admit that I am still not great in all those tricks you can do with x-order traversals and then rebuild stuff using invariants. But I will get there; | ajna | NORMAL | 2020-10-10T01:02:37.745214+00:00 | 2020-10-10T01:11:55.588112+00:00 | 1,185 | false | I have to admit that I am still not great in all those tricks you can do with x-order traversals and then rebuild stuff using invariants. But I will get there; for now, I just wanted to have fun, so I went to solve it my own way, creating an encoding of comma-separated values (similar to how you build trees in LC\'s input fields, just having empty strings instead of writing `"null"` there) on one hand and reading it on the others.\n\nTurned out my solution is still definitely efficient and can solve [a hard problem](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) without changing a single comma of it (okay, I admit before I set the value of empty nodes to `-1` and now I changed to `INT_MIN` to be compiant with the new rules, but that is about it).\n\nBut let\'s proceed in order:\n\n## Encoding Part\n\nAs usual, edge cases out of the table first: if the tree is empty, we return just an empty string.\n\nIf not, we declare a few variables:\n* `res`, a string initialised with the value of `root->val` converted to string;\n* `len`, to store the length of our queue (more about it in just about one line!), initialised to `1` (since we know at least `root` is a valid node);\n* `q`, a queue of `TreeNode` pointers, that we go and fill in immediately with `root`.\n\nThen we start with our BFS, which will loop as long as `len` is not `0`; inside, with another loop, we will keep removing the first `len` elements in front of the the queue and, for each one of them, we will:\n* assign it to `root` (no need to create a new variable here);\n* add a comma to `res`;\n* if we have `root->left`, then we will:\n\t* add the stringified version of its value to `res`;\n\t* add the node itself to `q`;\n* add another comma to `res`;\n* if we have `root->right`, then we will:\n\t* add the stringified version of its value to `res`;\n\t* add the node itself to `q`.\n\nIf you try to proceed step-by-step, you will see that this will convert a starting tree to a format rather similar to the one used in LC\'s custom inputs, just leaving an empty string where they put `"null"` as mentioned, to save space, and with possibly some extra trailing commas on the last level.\n\nIf you want to test yourself the logic with a non-trivial tree, try to put as a custom input `[100,90,110,80,95,105,115,70,null,null,98,104,106,null,200,60,75,null,99,null,null,null,107,116,201]` and it should give you back `"100,90,110,80,95,105,115,70,,,98,104,106,,200,60,75,,99,,,,107,116,201,,,,,,,,,,,,"`.\n\nOnce we are done, we can return `res` :)\n\n## Decoding Part\n\nSpecularly, first of all away with the edge cases: if the input string `ser` (short for "serialised", but also mirroring `res` above: how cool is that? Yeah, not much, but I am a simple man) is empty, we just return a `NULL` (=empty) tree.\n\nNow, support variables:\n* `len`, similar to the one above, preset to `1` and used for the BFS approach;\n* `nextVal`, where we will store what we read from each bit of serialisation;\n* `root`, initialised with the first value read from the `ser` and our result variable, and `curr`, both `TreeNode` pointers;\n* `q`, a queue of `TreeNode` pointers like the one above, initialised with `root`.\n\nEvery step of reading from the input string will be done using a class variable, `pos`, initialised to `0` and progressively incremented, and using the helper function `readString` that will take one character at a time (or no characters at all, for `NULL` nodes) to compose `res`, that will be then returned after being converted to a number (if not empty) or `INT_MIN` (if empty).\n\nIn our BFS, again same as above, we will loop until `len` is not `0` and internally we will extract at each round the first `len` nodes in front of `q`; I know here I could have just probably kept running until I had nodes in the queue, but I really enjoyed the symmetry of the 2 parts of the solution and I deem it important: elegant code is code that is more easily read, used and maintained.\n\nOr so I like to delude myself.\n\nAnyway, for each extracted node, we will:\n* read from the input string `ser` and assign it to `nextVal`;\n* if `nextVale` is not `INT_MIN`, we will then create a new `TreeNode` with that avalue, add it as a left branch to `curr` and push it into `q`;\n* read again from the input string `s` and assign it to `nextVal`;\n* if `nextVale` is not `INT_MIN`, we will then create a new `TreeNode` with that avalue, add it as a right branch to `curr` and push it into `q`,\n\nRinse and repeat until `q` is empty (`ser` will never be empty before it) and finally you can return `root` :)\n\nThe code:\n\n```cpp\nclass Codec {\npublic:\n // encoding logic\n string serialize(TreeNode* root) {\n // edge case out\n if (!root) return "";\n // support variables\n string res = to_string(root->val);\n int len = 1;\n queue<TreeNode*> q;\n q.push(root);\n\t\t// BFS here!\n while (len) {\n while(len--) {\n // extracting the front of the queue\n root = q.front();\n q.pop();\n res += \',\';\n if (root->left) {\n res += to_string(root->left->val);\n // adding the next node only if meaningful - if it has children\n q.push(root->left);\n }\n res += \',\';\n if (root->right) {\n res += to_string(root->right->val);\n // adding the next node only if meaningful - if it has children\n q.push(root->right);\n }\n }\n len = q.size();\n }\n return res;\n }\n \n // decoding logic\n int pos = 0;\n int readString(string &s) {\n string tmp = "";\n while(pos < s.size() && s[pos] != \',\') tmp += s[pos++];\n pos++;\n return tmp.size() ? stoi(tmp) : INT_MIN;\n }\n\n TreeNode* deserialize(string ser) {\n if (!ser.size()) return NULL;\n int len = 1, nextVal;\n TreeNode *root = new TreeNode(readString(ser)), *curr;\n queue<TreeNode*> q;\n q.push(root);\n while (len) {\n while(len--) {\n // extracting the front of the queue\n curr = q.front();\n q.pop();\n // adding left and right branches if present to both the tree and the queue\n nextVal = readString(ser);\n if (nextVal != INT_MIN) {\n curr->left = new TreeNode(nextVal);\n q.push(curr->left);\n }\n nextVal = readString(ser);\n if (nextVal != INT_MIN) {\n curr->right = new TreeNode(nextVal);\n q.push(curr->right);\n }\n }\n len = q.size();\n }\n return root;\n }\n};\n``` | 6 | 0 | ['Breadth-First Search', 'C', 'C++'] | 0 |
serialize-and-deserialize-bst | Python simple, clean and short solution | python-simple-clean-and-short-solution-b-t7f0 | \nclass Codec:\n def serialize(self, root: TreeNode) -> str:\n def encode(root):\n return "" if not root else str(root.val) + "-" + encode( | yehudisk | NORMAL | 2020-10-09T11:17:23.765032+00:00 | 2020-10-09T11:17:23.765108+00:00 | 423 | false | ```\nclass Codec:\n def serialize(self, root: TreeNode) -> str:\n def encode(root):\n return "" if not root else str(root.val) + "-" + encode(root.left)+encode(root.right)\n\n return encode(root)\n \n\n def deserialize(self, data: str) -> TreeNode:\n def insert(root, val):\n if not root:\n return TreeNode(val)\n\n if val <= root.val:\n root.left = insert(root.left,val)\n\n else:\n root.right = insert(root.right,val)\n\n return root\n \n root = None\n my_list = data.split("-")\n my_list.pop(len(my_list)-1)\n for item in my_list:\n root = insert(root, int(item));\n\n return root;\n```\n**Like it? please upvote...** | 6 | 3 | ['Python'] | 0 |
serialize-and-deserialize-bst | Java Solution with Explanation using an Example for better understanding | Queue | Preorder | java-solution-with-explanation-using-an-din12 | EXPLANATION\n\nTaking Example 1 of the question: BST = [2, 1, 3]\n\n1. SERIALIZE / ENCODE: Use Preorder Traversal to serialize the BST where each node value is | aayush912 | NORMAL | 2020-10-09T07:20:36.980502+00:00 | 2020-10-09T07:34:16.249308+00:00 | 431 | false | **EXPLANATION**\n\nTaking Example 1 of the question: ***BST = [2, 1, 3]***\n\n1. **SERIALIZE / ENCODE**: Use **Preorder Traversal** to serialize the BST where each node value is separated by a comma (**","**). So after serialization of the above tree, we will return a string like this: **2,1,3**.\n\n2. **DESERIALIZE / DECODE**: Here comes the importance of using **Preorder Traversal** in the above step. By doing this, we ensured that all the parent nodes (roots) come before the children nodes *(all **left** nodes followed by all **right** nodes)*. So all we have to do now is **Add** all the nodes in the string into a **Queue** and keep creating the tree node-by-node. For this, the steps are:\n\ni) Repeat the below steps until **queue** is not empty.\nii) Pop out a node from the front of the queue. If the node is not null, then create a new node by using it\'s value.\niii) Recursively call the *Deserialize Function* to store all the **left children** first and then again to store all the **right children** of a particular node.\niv) Return the node.\n\n*For example, our serialized string was **2,1,3***. So we add them in the queue one-by-one. So our **queue** looks like **[2,1,3]**.\n\nNow, popping **2** from the queue, we are left with **[1,3]**.\n\nRecursively call the function to store its left child. New node is **1**, and both its **left child** and **right child** will be stored as null in the next two recursive calls. So **1** gets stored as the **Left Child** of node **2**. Similarly, **3** gets stored as the **Right Child** of node **2**.\n\nIn the end, we return node **2** which is the root of the deserialized tree. That\'s it and you have your deserialized tree.\n\n*------Please **upvote** if you liked the solution. Please put your doubts/queries in the comments section below. I will try my best to answer them.------*\n```\npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize (TreeNode root) {\n if (root == null)\n return "";\n return String.valueOf (root.val) + "," + serialize (root.left) + "," + serialize (root.right);\n \n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize (String data) {\n String S [] = data.split (",");\n Queue <String> queue = new LinkedList ();\n for (String s: S)\n queue.add (s);\n return deserializeUtil (queue);\n }\n \n public TreeNode deserializeUtil (Queue <String> queue) {\n while (!queue.isEmpty ()) {\n String s = queue.poll ();\n if (s.equals (""))\n return null;\n TreeNode node = new TreeNode (Integer.valueOf (s));\n node.left = deserializeUtil (queue);\n node.right = deserializeUtil (queue);\n return node;\n }\n return null;\n }\n}\n``` | 6 | 1 | [] | 1 |
serialize-and-deserialize-bst | Easy to Understand Javascript Solution, 84ms, beats 91% | easy-to-understand-javascript-solution-8-ctw9 | Serialize: push all nodes\' value into an array in pre-order, and join them with \',\' or any non-numeric character\n\nvar serialize = function(root) {\n if | jiayuandeng | NORMAL | 2018-12-04T06:48:43.826978+00:00 | 2018-12-04T06:48:43.827019+00:00 | 415 | false | Serialize: push all nodes\' value into an array in pre-order, and join them with \',\' or any non-numeric character\n```\nvar serialize = function(root) {\n if (root === null) return \'\';\n let result = [];\n serializeHelper(root, result);\n return result.join(\',\');\n};\n\nconst serializeHelper = function(node, result) {\n if (node) {\n result.push(node.val);\n serializeHelper(node.left, result);\n serializeHelper(node.right, result);\n }\n};\n```\nDeserialize: Split the data to get the pre-order array. Here we know two facts:\n1. The input tree and all its sub-trees are BST, so all values from the left sub-tree are less than the value of root node, and all values from the right sub-tree are greater than the value of root node.\n2. The array is a pre-order traversal of the tree, which means root always comes first, then left sub-tree (could be missing), then right sub-tree (could be missing).\n\nSo, the tree can be reconstructed by:\n\n1. Set array[0] as root and remove it from the array. \n2. Check the new array[0]. It could be either root.left or root.right (when root.left is null). We can decide it by checking if array[0] is in the range of two sub-trees. These ranges are (currentLowerBound, root.val) and (root.val, currentUpperBound);\n3. Do the same thing recursively to left and right subtree.\n\n```\nvar deserialize = function(data) {\n if (!data) return null;\n const array = data.split(\',\');\n return deserializeHelper(array, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY);\n};\n\nconst deserializeHelper = function(array, min, max) {\n if (array.length === 0) return null;\n let val = +array[0];\n if (val < min || val > max) return null;\n array.shift();\n let root = new TreeNode(val);\n root.left = deserializeHelper(array, min, val);\n root.right = deserializeHelper(array, val, max);\n return root;\n};\n``` | 6 | 0 | [] | 1 |
serialize-and-deserialize-bst | Golang BFS solution O(n) | golang-bfs-solution-on-by-tuanbieber-jdi6 | \ntype Codec struct {\n}\n\nfunc Constructor() Codec {\n return Codec{}\n}\n\nfunc (this *Codec) serialize(root *TreeNode) string {\n var queue []*TreeNod | tuanbieber | NORMAL | 2022-03-14T05:44:54.585299+00:00 | 2022-03-14T05:44:54.585348+00:00 | 424 | false | ```\ntype Codec struct {\n}\n\nfunc Constructor() Codec {\n return Codec{}\n}\n\nfunc (this *Codec) serialize(root *TreeNode) string {\n var queue []*TreeNode\n\n\tenqueue(&queue, root)\n\n\tvar result string\n\n\tfor len(queue) > 0 {\n\t\tdequeuedElement := dequeue(&queue)\n\n\t\tif dequeuedElement != nil {\n\t\t\tresult = result + fmt.Sprintf("%v", dequeuedElement.Val) + ","\n\t\t\tenqueue(&queue, dequeuedElement.Left)\n\t\t\tenqueue(&queue, dequeuedElement.Right)\n\t\t} else {\n\t\t\tresult = result + "nil" + ","\n\t\t}\n\t}\n\n\treturn result[:len(result)-1]\n}\n\nfunc (this *Codec) deserialize(data string) *TreeNode { \n splittedData := strings.Split(data, ",")\n\n\tvar result []*TreeNode\n\n\tfor _, num := range splittedData {\n\t\tif num == "nil" {\n\t\t\tresult = append(result, nil)\n\t\t} else {\n\t\t\titem := TreeNode{\n\t\t\t\tVal: toInt(num),\n\t\t\t}\n\n\t\t\tresult = append(result, &item)\n\t\t}\n\t}\n \n begin := 0\n \n\tfor _, node := range result {\n\t\tif node == nil {\n continue\n\t\t} else {\n\t\t\tleft := 2 * begin + 1\n\t\t\tright := 2 * begin + 2\n\n\t\t\tif left < len(result) {\n\t\t\t\tnode.Left = result[left]\n\t\t\t}\n\n\t\t\tif right < len(result) {\n\t\t\t\tnode.Right = result[right]\n\t\t\t}\n \n begin++\n\t\t}\n\t}\n\n\treturn result[0]\n}\n\nfunc enqueue(queue *[]*TreeNode, newItem *TreeNode) {\n\tif queue == nil {\n\t\tpanic("nil pointer")\n\t}\n\n\t*queue = append(*queue, newItem)\n}\n\nfunc dequeue(queue *[]*TreeNode) *TreeNode {\n\tif queue == nil {\n\t\tpanic("nil pointer")\n\t}\n\n\tif len(*queue) == 0 {\n\t\tpanic("empty queue")\n\t}\n\n\tdequeuedElement := (*queue)[0]\n\n\t*queue = (*queue)[1:len(*queue)]\n\n\treturn dequeuedElement\n}\n\nfunc toInt(s string) int {\n\tvalue, err := strconv.Atoi(s)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn value\n}\n``` | 5 | 0 | ['Breadth-First Search', 'Go'] | 1 |
serialize-and-deserialize-bst | Simple C++ Code | Preorder Traversal | Queue | Easy to understand | simple-c-code-preorder-traversal-queue-e-q525 | \nclass Codec {\npublic:\n\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n if(!root) return "x,";\n string l= | khushboo2001 | NORMAL | 2021-05-08T10:35:52.255160+00:00 | 2021-05-08T10:35:52.255193+00:00 | 476 | false | ```\nclass Codec {\npublic:\n\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n if(!root) return "x,";\n string l=serialize(root->left);\n string r=serialize(root->right);\n return to_string(root->val)+","+l+r;\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n queue<string> q;\n string s="";\n for(int i=0;i<data.size();i++){\n if(data[i]==\',\'){\n q.push(s);\n s="";\n continue;\n }\n s+=data[i];\n }\n return helper(q);\n }\n \n TreeNode* helper(queue<string> &q){\n string ch=q.front();\n q.pop();\n if(ch=="x") return NULL;\n TreeNode* root=new TreeNode(stoi(ch));\n root->left=helper(q);\n root->right=helper(q);\n return root;\n }\n};\n``` | 5 | 1 | ['Recursion', 'Queue', 'C'] | 0 |
serialize-and-deserialize-bst | Java O(n) Iterative, no nulls | java-on-iterative-no-nulls-by-serdaroqua-w8es | The whole point of this question is to use the BST property to at get rid of nulls in your serialized string (Question #297). Anything less is a suboptimal solu | serdaroquai | NORMAL | 2018-12-23T20:36:57.481681+00:00 | 2018-12-23T20:36:57.481727+00:00 | 533 | false | The whole point of this question is to use the BST property to at get rid of nulls in your serialized string (Question #297). Anything less is a suboptimal solution.\n\n - To Serialize just do an iterative pre-order traversal. (in real world, recursive can stack overflow if BST is unbalanced)\n - To Deserialize:\n\t - if next node is smaller then parent just (left) add to parent.\n\t - if next node is larger then parent pop the stack until you find the largest parent you can (right) add to.\n\t - finally stack the next node as a candidate parent.\n\nEach node gets in and out of stack only once, so time complexity `O(n)`, and the serialized string has no nulls, or markers only the nodes.\n\n```java\n public String serialize(TreeNode n) {\n if (n == null) return "";\n StringBuilder sb = new StringBuilder();\n \n Stack<TreeNode> stack = new Stack<>();\n while (n!=null) {\n sb.append(n.val).append(",");\n if (n.right != null) stack.push(n.right);\n n = (n.left == null && !stack.isEmpty()) ? stack.pop() : n.left;\n }\n sb.setLength(sb.length()-1);\n return sb.toString();\n }\n\n public TreeNode deserialize(String s) {\n if ("".equals(s)) return null;\n String[] tokens = s.split(",");\n \n Stack<TreeNode> stack = new Stack<>();\n TreeNode head = new TreeNode(Integer.valueOf(tokens[0]));\n stack.push(head);\n \n for (int i=1;i<tokens.length;i++) {\n \n TreeNode parent = stack.peek();\n TreeNode next = new TreeNode(Integer.valueOf(tokens[i]));\n \n if (next.val < parent.val) parent.left = next;\n else {\n parent = stack.pop();\n while (!stack.isEmpty() && next.val > stack.peek().val) parent = stack.pop();\n parent.right = next;\n }\n stack.push(next);\n }\n return head;\n }\n``` | 5 | 0 | [] | 0 |
serialize-and-deserialize-bst | Java O(N) recursive solution | java-on-recursive-solution-by-yipqiy-pcaw | ```\n// Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n if (root == null) {\n return ".";\n }\n | yipqiy | NORMAL | 2016-12-15T06:00:06.545000+00:00 | 2016-12-15T06:00:06.545000+00:00 | 1,912 | false | ```\n// Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n if (root == null) {\n return "*.";\n }\n StringBuilder sb = new StringBuilder();\n sb.append(root.val);\n if (root.left == null && root.right == null) {\n sb.append("*.");\n return sb.toString();\n }\n sb.append(".");\n sb.append(serialize(root.left));\n sb.append(serialize(root.right));\n return sb.toString();\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n int[] begin = {0};\n return deserializeMethod(data, begin);\n }\n\n private TreeNode deserializeMethod(String data, int[] begin) {\n int index = data.indexOf(".", begin[0]);\n TreeNode node = null;\n if (data.charAt(index - 1) == '*') {\n String str = data.substring(begin[0], index - 1);\n begin[0] = index + 1;\n if (str.equals("")) {\n return null;\n }\n node = new TreeNode(Integer.parseInt(str));\n } else {\n String str = data.substring(begin[0], index);\n begin[0] = index + 1;\n node = new TreeNode(Integer.parseInt(str));\n node.left = deserializeMethod(data, begin);\n node.right = deserializeMethod(data, begin);\n }\n return node;\n } | 5 | 0 | [] | 0 |
serialize-and-deserialize-bst | Preorder serialize and recursive deserialize C++ 26ms | preorder-serialize-and-recursive-deseria-v3b5 | ```\nclass Codec {\npublic:\n //Encodes a tree to a single string.\n void serialize(TreeNode root, vector &val)\n {\n if(root == NULL) return;\n | freeprogrammer | NORMAL | 2017-02-01T15:52:48.892000+00:00 | 2018-09-11T09:28:30.699428+00:00 | 1,914 | false | ```\nclass Codec {\npublic:\n //Encodes a tree to a single string.\n void serialize(TreeNode* root, vector<int> &val)\n {\n if(root == NULL) return;\n val.push_back(root->val);\n serialize(root->left, val);\n serialize(root->right, val);\n }\n\n string serialize(TreeNode* root) {\n vector<int> val;\n serialize(root, val);\n char *p = (char*)val.data();\n string str(p, val.size() * sizeof(int));\n return str;\n }\n \n // deserialize val[l .. r]\n TreeNode* deserializeSubtree(int *val, int l, int r)\n {\n if(l > r) return NULL;\n TreeNode *subRoot = new TreeNode(val[l]);\n int i = l+1;\n while(i <= r && val[i] < val[l]) ++i; \n subRoot->left = deserializeSubtree(val, l+1, i-1);\n subRoot->right = deserializeSubtree(val, i, r);\n return subRoot;\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n //preorder traversed string\n int n = data.size() / sizeof(int);\n TreeNode *root = deserializeSubtree((int*)data.data(), 0, n-1);\n return root;\n }\n \n}; | 5 | 0 | [] | 2 |
serialize-and-deserialize-bst | Very simple and easy solution. | very-simple-and-easy-solution-by-srh_abh-zjj2 | \n\n# Code\npython3 []\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = Non | srh_abhay | NORMAL | 2024-09-08T12:10:55.358622+00:00 | 2024-09-08T12:11:48.015604+00:00 | 612 | false | \n\n# Code\n```python3 []\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Codec:\n\n def serialize(self, root: Optional[TreeNode]) -> str:\n if not root:\n return ""\n \n queue = deque([root])\n output = []\n \n while queue:\n current = queue.popleft()\n if current:\n output.append(str(current.val))\n queue.append(current.left)\n queue.append(current.right)\n else:\n output.append("null")\n \n # Join the list into a comma-separated string\n return ",".join(output)\n\n def deserialize(self, data: str) -> Optional[TreeNode]:\n if not data:\n return None\n \n nodes = data.split(",")\n root = TreeNode(int(nodes[0]))\n queue = deque([root])\n i = 1\n \n while queue:\n current = queue.popleft()\n \n # Handle left child\n if nodes[i] != "null":\n current.left = TreeNode(int(nodes[i]))\n queue.append(current.left)\n i += 1\n \n # Handle right child\n if nodes[i] != "null":\n current.right = TreeNode(int(nodes[i]))\n queue.append(current.right)\n i += 1\n \n return root\n\n# Example usage:\n# ser = Codec()\n# deser = Codec()\n# tree = ser.serialize(root)\n# ans = deser.deserialize(tree)\n# return ans\n\n``` | 4 | 0 | ['Python3'] | 0 |
serialize-and-deserialize-bst | Simple solution using level order traversal. | simple-solution-using-level-order-traver-qx60 | \n# Complexity\n- Time complexity:O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(N)\n Add your space complexity here, e.g. O(n) \n\n# | ShivamDubey55555 | NORMAL | 2023-03-06T05:25:54.353400+00:00 | 2023-03-06T05:25:54.353428+00:00 | 572 | false | \n# Complexity\n- Time complexity:$$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\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\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n if(root == NULL) return "";\n\n string s = "";\n queue<TreeNode*>q;\n q.push(root);\n while(!q.empty()){\n TreeNode *currNode = q.front();\n q.pop();\n if(currNode == NULL) s.append("#,");\n else s.append(to_string(currNode->val) + \',\');\n if(currNode != NULL){\n q.push(currNode->left);\n q.push(currNode->right);\n }\n }\n return s;\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n if(data.size() == 0) return NULL;\n stringstream s(data);\n string str;\n getline(s,str,\',\');\n TreeNode*root = new TreeNode(stoi(str));\n queue<TreeNode*>q;\n q.push(root);\n while(!q.empty()){\n TreeNode * node = q.front();\n q.pop();\n\n getline(s,str,\',\');\n if(str == "#"){\n node->left = NULL;\n }\n else{\n TreeNode* leftNode = new TreeNode(stoi(str));\n node->left = leftNode;\n q.push(leftNode);\n }\n getline(s,str,\',\');\n if(str == "#"){\n node->right = NULL;\n }\n else{\n TreeNode* rightNode = new TreeNode(stoi(str));\n node->right = rightNode;\n q.push(rightNode);\n }\n }\n return 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``` | 4 | 0 | ['C++'] | 0 |
serialize-and-deserialize-bst | c++ | Preorder Traversal | Easy to understand | c-preorder-traversal-easy-to-understand-btcsi | \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 | akshat0610 | NORMAL | 2022-10-25T17:51:20.098204+00:00 | 2022-10-25T17:51:20.098300+00:00 | 950 | false | ```\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``` | 4 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Binary Search Tree', 'C', 'C++'] | 1 |
serialize-and-deserialize-bst | c++ | Preorder Traversal | Easy to understand | c-preorder-traversal-easy-to-understand-8kyyq | \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( | venomhighs7 | NORMAL | 2022-10-08T03:53:29.165441+00:00 | 2022-10-08T03:53:29.165483+00:00 | 1,072 | false | \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``` | 4 | 0 | ['C++'] | 0 |
serialize-and-deserialize-bst | Simple, straightforward Java solution | simple-straightforward-java-solution-by-cihaj | Simple and easy to understand Java solution.\n(Not the most efficient, due to the simple deserialization approach)\n\n\n // since this is a binary search tre | Tim_P | NORMAL | 2021-07-27T08:04:12.154801+00:00 | 2021-07-27T08:04:12.154834+00:00 | 871 | false | Simple and easy to understand Java solution.\n(Not the most efficient, due to the simple deserialization approach)\n\n```\n // since this is a binary search tree, we\'ll just output values in BFS\n // order (when serializind), then add all values to the tree one by one (when deserializing)\n // serialize will take O(n)\n // deserialize will take O(n*h), where h is the height of the tree (n in the\n // worst case, and log(n) if the tree is balanced)\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n if (root == null) {\n return null;\n }\n \n StringBuilder sb = new StringBuilder();\n Queue<TreeNode> q = new LinkedList<>();\n q.add(root);\n while (!q.isEmpty()) {\n TreeNode n = q.remove();\n sb.append(n.val).append(\',\');\n if (n.left != null)\n q.add(n.left);\n if (n.right != null)\n q.add(n.right);\n }\n sb.setLength(sb.length()-1); // remove last \',\'\n return sb.toString();\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n if (data == null) {\n return null;\n }\n \n String[] vals = data.split(",");\n TreeNode root = new TreeNode(Integer.parseInt(vals[0]));\n for (int i=1; i<vals.length; i++) {\n add(root, Integer.parseInt(vals[i]));\n }\n return root;\n }\n \n private static void add(TreeNode root, int val) {\n TreeNode cur = root;\n TreeNode parent = null;\n while (cur != null) {\n parent = cur;\n cur = (val <= cur.val) ? cur.left : cur.right;\n }\n if (val <= parent.val) {\n parent.left = new TreeNode(val);\n } else {\n parent.right = new TreeNode(val);\n }\n }\n\t``` | 4 | 0 | ['Breadth-First Search', 'Java'] | 1 |
serialize-and-deserialize-bst | Simple C++ Solution, Comment your thoughts: Time and Space O(N) | simple-c-solution-comment-your-thoughts-p25of | \nclass Codec {\npublic:\n\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n if(!root){\n return "NULL";\n | level7 | NORMAL | 2021-03-05T13:44:56.106427+00:00 | 2021-03-05T13:44:56.106467+00:00 | 415 | false | ```\nclass Codec {\npublic:\n\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n if(!root){\n return "NULL";\n }\n \n string left = serialize(root->left);\n string right = serialize(root->right);\n \n return to_string(root->val) + " " + left + " " + right;\n }\n \n TreeNode* helper_des(stringstream& ss, string s) {\n ss >> s;\n if(s == "NULL"){\n return NULL;\n }\n \n TreeNode* root = new TreeNode(stoi(s));\n \n root->left = helper_des(ss, s);\n root->right = helper_des(ss, s);\n \n return root;\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n stringstream ss(data);\n return helper_des(ss, "");\n }\n};\n``` | 4 | 0 | ['C'] | 1 |
serialize-and-deserialize-bst | easy java solution using bst property similiar to validating bst problem | easy-java-solution-using-bst-property-si-t84g | \n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) | ajithbabu | NORMAL | 2021-03-03T09:13:29.311627+00:00 | 2021-03-03T09:13:29.311660+00:00 | 978 | false | ```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\npublic class Codec {\n\n int serializedTreeIndexPointer;\n public String serialize(TreeNode root) {\n StringBuilder serializedTree = new StringBuilder();\n preorder(root, serializedTree);\n return serializedTree.toString();\n }\n \n void preorder(TreeNode root, StringBuilder serializedTree) {\n if (root == null) {\n return;\n }\n\n serializedTree.append(root.val).append(",");\n preorder(root.left, serializedTree);\n preorder(root.right, serializedTree);\n }\n\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String serializedTree) {\n serializedTreeIndexPointer = 0;\n String serializedArray[] = serializedTree.split(",");\n return treeBuilder(serializedArray, Integer.MIN_VALUE, Integer.MAX_VALUE);\n\n }\n \n TreeNode treeBuilder(String serializedArray[], int min, int max) {\n if (serializedTreeIndexPointer >= serializedArray.length)\n return null;\n \n Integer a = parseStringToInt(serializedArray[serializedTreeIndexPointer]);\n if ( a == null || a > max || a < min) {\n return null;\n }\n\n TreeNode root = new TreeNode(Integer.parseInt(serializedArray[serializedTreeIndexPointer++]));\n root.left = treeBuilder(serializedArray, min, root.val);\n root.right = treeBuilder(serializedArray, root.val, max);\n \n return root;\n }\n \n Integer parseStringToInt(String s) {\n try {\n return Integer.parseInt(s);\n }\n catch (NumberFormatException e) {\n return null;}\n }\n}\n``` | 4 | 0 | ['Binary Search Tree', 'Java'] | 1 |
serialize-and-deserialize-bst | Python3 Solution Explained (video + code) (inorder + preorder) | python3-solution-explained-video-code-in-cxe8 | \nhttps://www.youtube.com/watch?v=g6Q1cpQvz8A\n\nclass Codec:\n\n def serialize(self, root: TreeNode) -> str:\n """Encodes a tree to a single string.\ | spec_he123 | NORMAL | 2020-10-10T05:57:03.952090+00:00 | 2020-10-10T05:57:03.952134+00:00 | 687 | false | [](https://www.youtube.com/watch?v=g6Q1cpQvz8A)\nhttps://www.youtube.com/watch?v=g6Q1cpQvz8A\n```\nclass Codec:\n\n def serialize(self, root: TreeNode) -> str:\n """Encodes a tree to a single string.\n """\n res = []\n \n def preorder(root):\n if root:\n res.append(str(root.val))\n preorder(root.left)\n preorder(root.right)\n \n preorder(root)\n return " ".join(res)\n\n def deserialize(self, data: str) -> TreeNode:\n """Decodes your encoded data to tree.\n """\n data = [int(x) for x in data.split()]\n \n def build(pre, inorder):\n if not pre:\n return None\n \n node = TreeNode(pre[0])\n temp = inorder.index(node.val)\n node.left = build(pre[1: temp + 1], inorder[:temp])\n node.right = build(pre[temp + 1 :], inorder[temp + 1 :])\n \n return node\n \n return build(data, sorted(data))\n``` | 4 | 0 | ['Python3'] | 1 |
serialize-and-deserialize-bst | Python [recursion] | python-recursion-by-gsan-9h39 | Serialize the pre-order traversal into a string. Reconstruct from this representation. Both functions can be implemented by recursion.\n\n\nclass Codec:\n de | gsan | NORMAL | 2020-10-09T07:56:10.910638+00:00 | 2020-10-09T07:56:10.910680+00:00 | 291 | false | Serialize the pre-order traversal into a string. Reconstruct from this representation. Both functions can be implemented by recursion.\n\n```\nclass Codec:\n def serialize(self, root: TreeNode) -> str:\n if not root:\n return \'\'\n s1 = self.serialize(root.left)\n s2 = self.serialize(root.right)\n ret = str(root.val)\n if s1: ret += \' \' + s1\n if s2: ret += \' \' + s2\n return ret\n\n def deserialize(self, data: str) -> TreeNode:\n if not data:\n return []\n def recur(arr):\n this = TreeNode(arr[0])\n left = [e for e in arr[1:] if e<arr[0]]\n right = [e for e in arr[1:] if e>arr[0]]\n if left: this.left = recur(left)\n if right: this.right = recur(right)\n return this\n arr = data.strip().split(\' \')\n arr = [int(e) for e in arr]\n return recur(arr)\n``` | 4 | 0 | [] | 0 |
serialize-and-deserialize-bst | C : custom low-level data mapping - no strings, no recursion, no built-in DS - simple n short | c-custom-low-level-data-mapping-no-strin-zov7 | Context : This solution of mine uses a custom low-level raw data mapping representaion. There is no string parsing involved, no recursive approach is being used | universalcoder12 | NORMAL | 2020-07-13T00:49:12.827457+00:00 | 2020-07-20T18:10:49.469600+00:00 | 185 | false | **Context :** This solution of mine uses a custom low-level raw data mapping representaion. There is no string parsing involved, no recursive approach is being used, and no built-in Data Structures are used. I have kept this code like all of my other published code as barebone C code as possible.\n\n**Details :** Before arriving at below custom data representation, I gave the string approach a try and was way slower due to the overhead in parsing, etc. So, I decided to redesign this in terms of my own custom data representation. In this representation, each of the node\'s address\'s LS-16bits act as key which get mapped onto unique 1-indexed numbers. These mapped indexes are then used as offsets for each of those nodes. Each node will refer to its child nodes using those offsets. Each node in the sequence of such nodes will hold the value of a specific node and its left-child-off and right-child-off. It took considerable time to get to this far but I feel it\'s totally worth it!\n\n**NOTE :** My below solution works for both BST and Binary Tree as there is no dependency on the structure or organization of the nodes or values therin. Just choose the key/mask width as per the address-range(LS-bits) of node addresses. As I observed, for the other Binary Tree case, I had to consider at least 17 lower bits of node addresses for their unique mapping whereas for the below BST, 16 lower bits were sufficient. Hence, I use appropriate width for key type as uint32_t(for 17-bits case) and uint16_t(for 16-bits case) controlled by WIDE_RANGE feature macro.\n\n```\n//#define WIDE_RANGE\n\n#ifdef WIDE_RANGE\n#define KEY_MASK 0x1ffff\ntypedef uint32_t keyy_t;\n#else\n#define KEY_MASK 0xffff\ntypedef uint16_t keyy_t;\n#endif // WIDE_RANGE\n\n#define KEY(a) ((uintptr_t)(a) & KEY_MASK)\n\nstruct srlz_data {\n int val;\n keyy_t loff, roff; \n} __attribute__ ((packed));\n\nstruct srlz {\n size_t sz; // To help on-disk storage/retrieval, etc\n size_t n;\n struct srlz_data z[100000];\n} __attribute__ ((packed));\n \nchar* serialize(struct TreeNode* root) {\n int of[KEY_MASK] = { 0 }, i = 1, k;\n struct TreeNode *n[10000] = { root };\n struct srlz *d = malloc(sizeof *d);\n struct srlz_data *z = d->z;\n d->sz = sizeof *d;\n of[KEY(root)] = i++; \n for (int f = 0, b = 1 ; root && f < b ; f++) {\n z[of[k = KEY(n[f])]].val = n[f]->val;\n z[of[k]].loff = n[f]->left ? of[KEY(n[b++] = n[f]->left)] = i++ : 0;\n z[of[k]].roff = n[f]->right ? of[KEY(n[b++] = n[f]->right)] = i++ : 0;\n }\n return d->n = root ? i : 0, (char *)d;\n}\n\nstruct TreeNode* deserialize(char* data) {\n struct srlz *d = (void *)data;\n struct srlz_data *z = d->z + 1;\n size_t c = d->n;\n struct TreeNode *n[100000] = { [1] = c ? malloc(sizeof **n) : NULL };\n for (int i = 1 ; i < c ; n[i++]->val = z++->val) {\n n[i]->left = z->loff ? n[z->loff] = malloc(sizeof **n) : NULL;\n n[i]->right = z->roff ? n[z->roff] = malloc(sizeof **n) : NULL;\n }\n return n[1];\n}\n``` | 4 | 0 | ['C'] | 0 |
serialize-and-deserialize-bst | Java, bfs, queue | java-bfs-queue-by-chuanqiu-j3vf | \npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n StringBuilder sb = new StringBuilder( | chuanqiu | NORMAL | 2020-05-19T21:12:02.233013+00:00 | 2020-05-19T21:12:02.233058+00:00 | 248 | false | ```\npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n StringBuilder sb = new StringBuilder();\n if(root ==null) return sb.toString();\n Queue<TreeNode> q = new LinkedList<>();\n q.add(root);\n while(!q.isEmpty()){\n TreeNode node = q.poll();\n if(node !=null){\n q.add(node.left);\n q.add(node.right);\n sb.append(node.val+",");\n }else{\n sb.append("#"+",");\n }\n }\n return sb.toString();\n \n }\n\n // Decodes encoded data to tree.\n public TreeNode deserialize(String data) {\n TreeNode head = null;\n if(data ==null || data.length() ==0) return head;\n String[] nodes = data.split(",");//get elements include null;\n TreeNode[] treeNodes = new TreeNode[nodes.length];//get a TreeNode array\n for(int i = 0; i<nodes.length; i++){\n if(! nodes[i].equals("#") )\n treeNodes[i] = new TreeNode(Integer.valueOf(nodes[i]));//change non-null elem into node\n }\n for(int i =0,j=1; j<treeNodes.length;i++){\n if(treeNodes[i] != null){\n treeNodes[i].left = treeNodes[j++];\n treeNodes[i].right = treeNodes[j++];\n }\n }\n return treeNodes[0]; \n }\n}\n\n``` | 4 | 1 | [] | 1 |
serialize-and-deserialize-bst | 💡JavaScript Solution - Preorder | javascript-solution-preorder-by-aminick-7n7r | The idea\n1. Utilize the fact BST can be reconstructed from preorder/postorder array\njavascript\nvar serialize = function(root) {\n let preorder = [];\n | aminick | NORMAL | 2020-01-31T11:32:48.652350+00:00 | 2020-01-31T11:32:48.652383+00:00 | 666 | false | ### The idea\n1. Utilize the fact BST can be reconstructed from preorder/postorder array\n``` javascript\nvar serialize = function(root) {\n let preorder = [];\n let dfs = function(node) {\n if (node==null) return;\n preorder.push(node.val);\n dfs(node.left);\n dfs(node.right);\n }\n dfs(root);\n return preorder.join(\',\');\n};\n\n var deserialize = function(data) {\n if (data == \'\') return null;\n let preorder = data.split(\',\');\n let recur = function(lower, upper) {\n if (Number(preorder[0]) < lower || Number(preorder[0]) > upper) return null;\n if (preorder.length == 0) return null;\n let root = new TreeNode(preorder.shift());\n root.left = recur(lower, root.val);\n root.right = recur(root.val, upper);\n return root;\n }\n return recur(-Infinity, Infinity);\n};\n\n/**\n * Your functions will be called as such:\n * deserialize(serialize(root));\n */\n``` | 4 | 0 | ['JavaScript'] | 1 |
serialize-and-deserialize-bst | Recursive Preorder Python Solution - 20 lines | recursive-preorder-python-solution-20-li-mc4z | ```\nclass Codec:\n \n def serialize(self, root):\n if not root: return\n def serializeTree(node):\n if not node:\n | shaw3257 | NORMAL | 2018-08-31T18:19:19.720632+00:00 | 2018-10-25T19:37:24.064848+00:00 | 774 | false | ```\nclass Codec:\n \n def serialize(self, root):\n if not root: return\n def serializeTree(node):\n if not node:\n return \'null\'\n return str(node.val) + "," + serializeTree(node.left) + "," + serializeTree(node.right)\n return serializeTree(root)\n \n\n def deserialize(self, data):\n if not data: return \n def deserializeTree(a, i):\n if i >= len(a) or a[i] == \'null\': \n return [None, i + 1]\n else:\n node = TreeNode(a[i])\n node.left, j = deserializeTree(a, i + 1)\n node.right, j = deserializeTree(a, j) \n return [node, j]\n return deserializeTree(data.split(\',\'), 0)[0] | 4 | 0 | [] | 0 |
serialize-and-deserialize-bst | 2 concise Java Solutions (O(n) and O(n2)) with using BST's feature (Not the old generic solution for Binary Tree) | 2-concise-java-solutions-on-and-on2-with-ffpb | Idea:\nWe are given a BST, so it is possible to reconstruct the tree by using Pre-Order traverse array.\n\nNotice we have 1 requirement "The encoded string shou | nathanni | NORMAL | 2016-12-02T07:43:48.749000+00:00 | 2018-09-21T17:49:23.092219+00:00 | 370 | false | **Idea:**\nWe are given a BST, so it is possible to **reconstruct the tree by using Pre-Order traverse array**.\n\n*Notice we have 1 requirement "The encoded string should be as compact as possible." So let us forget the generic BFS/DFS solution for Binary Tree (Adding "#" or "NULL" for empty node)*\n\n\nSerialize:\nVery straightforward, simplify do a pre-order traverse and append to String.\n\n* Version 1: Two lines\n```\n public String serialize(TreeNode root) {\n if (root == null) return "";\n return root.val + "," + serialize(root.left) + serialize(root.right);\n }\n```\n\n* Version 2: Use StringBuilder to save a little bit time.\n```\n public String serialize(TreeNode root) {\n if (root == null) return "";\n StringBuilder sb = new StringBuilder();\n sb.append(root.val).append(",");\n sb.append(serialize(root.left));\n sb.append(serialize(root.right));\n return sb.toString();\n }\n```\n\nDeserialize\nSince we have a pre-order array. We always know the **first element is the root**. \nSo our strategy is to cut the array into different parts by appyling BST feature.\n\n* Version 1: O(N2)\n1.Passing start bound and end bound to helper function, which means to reconstruct tree in this scope (start ~ end).\n2.Find the first element larger than current root, the first element index will be the middle cutting point. Which means all elements left to it need to be the **root.left**, all elements right after it need to be **root.right**. Recursively call the helper function.\n```\n public TreeNode deserialize(String data) {\n if (data == null || data.length() == 0) return null;\n String[] sArr = data.split(",");\n return helper(sArr, 0, sArr.length - 1);\n }\n \n public TreeNode helper(String[] sArr, int start, int end) {\n if (start > end) return null;\n if (start == end) return new TreeNode(Integer.parseInt(sArr[start]));\n TreeNode node = new TreeNode(Integer.parseInt(sArr[start]));\n int mid = start + 1;\n while (mid <= end) {\n if (Integer.parseInt(sArr[mid]) > Integer.parseInt(sArr[start])) {\n break;\n }\n mid++;\n }\n node.left = helper(sArr, start + 1, mid - 1);\n node.right = helper(sArr, mid, end);\n return node;\n }\n```\n\n\n* Version 2: O(N)\n1.Similar id to @cccrrryyy 's solution: https://discuss.leetcode.com/topic/66495/using-lower-bound-and-upper-bound-to-deserialize-bst\n2.Pass a **min value (low bound)** and a **max value (high bound)** to helper function. \n3.I use **int[] currIdx** to simulate a static index variable, cuz I really don't like using a static/member/global variable.\n```\n public TreeNode deserialize(String data) {\n if (data == null || data.length() == 0) return null;\n String[] sArr = data.split(",");\n int[] currIdx = {0};\n return helper(sArr, currIdx, Integer.MIN_VALUE, Integer.MAX_VALUE);\n }\n \n public TreeNode helper(String[] sArr, int[] currIdx, int min, int max) {\n if (currIdx[0] > sArr.length - 1) return null;\n int curr = Integer.parseInt(sArr[currIdx[0]]);\n\n if (curr < min || curr > max) return null;\n\n TreeNode node = new TreeNode(curr);\n currIdx[0]++;\n node.left = helper(sArr, currIdx, min, curr);\n node.right = helper(sArr, currIdx, curr, max);\n return node;\n\n } | 4 | 0 | [] | 0 |
serialize-and-deserialize-bst | Simple Python preorder | simple-python-preorder-by-realisking-9h8x | In serialize step we do a preorder traversal to get the string. For reconstructing the BST, l and r are the left and right boundaries of our current array. Sinc | realisking | NORMAL | 2017-04-07T11:56:08.869000+00:00 | 2017-04-07T11:56:08.869000+00:00 | 428 | false | In ```serialize``` step we do a preorder traversal to get the string. For reconstructing the BST, ```l``` and ```r``` are the left and right boundaries of our ```current``` array. Since it's preorder traversal, for root value ```A[l]```, once we find the first point ```A[mid] < A[l]```, we know all values from this point until the right boundary are for the right subtree, and points before that until left boundary are the left subtree.\n```\nclass Codec:\n\n def serialize(self, root):\n """Encodes a tree to a single string.\n \n :type root: TreeNode\n :rtype: str\n """\n def preorder(node):\n if node:\n res.append(str(node.val))\n preorder(node.left)\n preorder(node.right)\n res = []\n preorder(root)\n return " ".join(res)\n \n\n def deserialize(self, data):\n """Decodes your encoded data to tree.\n \n :type data: str\n :rtype: TreeNode\n """\n def build(l, r):\n if l >= r: return None\n root = TreeNode(A[l])\n mid = l+1\n while mid < r and A[mid] < root.val: mid += 1\n root.left = build(l+1, mid)\n root.right = build(mid, r)\n return root\n \n A = map(int, data.split())\n return build(0, len(A))\n``` | 4 | 0 | [] | 0 |
serialize-and-deserialize-bst | A few solutions | a-few-solutions-by-claytonjwong-y1us | Whitespace delimited serialization/deserialization of the pre-order traversal of the tree. null values are represented as -1.\n\n---\n\nKotlin\n\nclass Codec() | claytonjwong | NORMAL | 2017-07-31T19:53:26.365000+00:00 | 2021-05-26T15:11:44.514429+00:00 | 437 | false | Whitespace delimited serialization/deserialization of the pre-order traversal of the tree. `null` values are represented as `-1`.\n\n---\n\n*Kotlin*\n```\nclass Codec() {\n fun serialize(root: TreeNode?): String {\n var A = mutableListOf<Int>()\n fun go(node: TreeNode? = root) {\n if (node == null) {\n A.add(-1)\n return\n }\n A.add(node?.`val`)\n go(node?.left)\n go(node?.right)\n }\n go()\n return A.joinToString(" ")\n }\n fun deserialize(S: String): TreeNode? {\n var A = ArrayDeque<Int>(S.split(" ").map{ it.toInt() })\n fun go(): TreeNode? {\n if (A.size == 0)\n return null\n var x = A.removeFirst().toInt()\n var root = if (-1 < x) TreeNode(x) else null\n root?.left = go()\n root?.right = go()\n return root\n }\n return go()\n }\n}\n```\n\n*Javascript*\n```\nlet serialize = (root, q = []) => {\n let go = root => {\n if (!root) {\n q.push(-1);\n return;\n }\n q.push(root.val);\n go(root.left);\n go(root.right);\n };\n go(root);\n return q.join(\' \');\n};\nlet deserialize = (data, q = data.split(\' \')) => {\n let go = () => {\n if (!q.length)\n return;\n let x = q.shift();\n let root = -1 < x ? new TreeNode(x) : null;\n if (root) root.left = go();\n if (root) root.right = go();\n return root;\n };\n return go();\n};\n```\n\n*Python3*\n```\nclass Codec:\n def serialize(self, root: TreeNode) -> str:\n q = []\n def go(root):\n if not root:\n q.append(-1)\n return\n q.append(root.val)\n go(root.left)\n go(root.right)\n go(root)\n return \' \'.join([str(x) for x in q])\n\n def deserialize(self, data: str) -> TreeNode:\n q = deque([int(s) for s in data.split(\' \')])\n def go():\n if not len(q):\n return\n x = q.popleft()\n root = TreeNode(x) if -1 < x else None\n if root: root.left = go()\n if root: root.right = go()\n return root\n return go()\n```\n\n*C++*\n```\nclass Codec {\npublic:\n using fun1 = function<void(TreeNode*)>;\n using fun2 = function<TreeNode*()>;\n string serialize(TreeNode* root, vector<int> q = {}) {\n fun1 go = [&](auto root) {\n if (!root) {\n q.push_back(-1);\n return;\n }\n q.push_back(root->val);\n go(root->left);\n go(root->right);\n };\n go(root);\n ostringstream stream; copy(q.begin(), q.end(), ostream_iterator<int>(stream, " "));\n return stream.str();\n }\n TreeNode* deserialize(string data) {\n istringstream stream{ data };\n fun2 go = [&](int x = 0) -> TreeNode* {\n if (!(stream >> x))\n return nullptr;\n auto root = -1 < x ? new TreeNode(x) : nullptr;\n if (root) root->left = go();\n if (root) root->right = go();\n return root;\n };\n return go();\n }\n};\n``` | 4 | 2 | [] | 0 |
serialize-and-deserialize-bst | short and clean solution | short-and-clean-solution-by-__abcd-t84r | \nclass Codec {\npublic:\n\n string serialize(TreeNode* root) {\n if(!root)return "#";\n return to_string(root->val)+"#"+serialize(root->left) | __Abcd__ | NORMAL | 2022-10-27T05:07:56.645914+00:00 | 2022-10-27T05:07:56.645961+00:00 | 757 | false | ```\nclass Codec {\npublic:\n\n string serialize(TreeNode* root) {\n if(!root)return "#";\n return to_string(root->val)+"#"+serialize(root->left) + serialize(root->right);\n }\n TreeNode* decode(stringstream& take,string res = ""){\n getline(take,res,\'#\');\n if(res.empty())return NULL;\n \n TreeNode* root= new TreeNode(stoi(res));\n root->left = decode(take), root->right = decode(take);\n return root;\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n stringstream take(data);\n return decode(take);\n }\n};\n\n``` | 3 | 0 | ['C'] | 0 |
serialize-and-deserialize-bst | Python - DFS || Easy and Simple Solution | python-dfs-easy-and-simple-solution-by-d-wtjf | \nclass Codec:\n def serialize(self, root: Optional[TreeNode]) -> str:\n res = []\n \n def dfs(node):\n if not node:\n | dayaniravi123 | NORMAL | 2022-04-11T14:57:04.293435+00:00 | 2022-04-11T14:57:04.293478+00:00 | 474 | false | ```\nclass Codec:\n def serialize(self, root: Optional[TreeNode]) -> str:\n res = []\n \n def dfs(node):\n if not node:\n res.append("N")\n return\n res.append(str(node.val))\n dfs(node.left)\n dfs(node.right)\n \n dfs(root)\n return ",".join(res)\n \n def deserialize(self, data: str) -> Optional[TreeNode]:\n vals = data.split(",")\n self.i = 0\n \n def dfs():\n if vals[self.i] == "N":\n self.i += 1\n return None\n node = TreeNode(int(vals[self.i]))\n self.i += 1\n node.left = dfs()\n node.right = dfs()\n return node\n return dfs()\n``` | 3 | 0 | ['Depth-First Search', 'Python3'] | 0 |
serialize-and-deserialize-bst | [Java] Solution - Level Order Traversal | java-solution-level-order-traversal-by-r-5q4y | Level Order Traversal\nNote that this is not the most compact solution and that this does not use the special property of binary search tree. It\'s however simp | repititionismastery | NORMAL | 2021-04-18T07:16:36.419652+00:00 | 2021-04-18T07:33:29.466645+00:00 | 207 | false | # Level Order Traversal\nNote that this is not the most compact solution and that this does not use the special property of binary search tree. It\'s however simple to implement and does the job.\n\nTo Serialize:\n* We traverse the BST in level order.\n* We use a separator and append the node values to our string. We use `blank` (i.e. `""`) character for the nulls to save some space.\n\nTo Deserialize:\n* We split the string by separator.\n* With the way we have serialized (we had also put nulls for all nodes) can use the binary tree property that for a parent at index `i`:\n * the left child will be at position `2 * i + 1`\n * the right child will be at position `2 * i + 2`\n* We construct the tree by using queue. We process parent nodes and enqueue child nodes and continue this process until queue is empty.\n\n```\npublic class Codec {\n \n public static final String SEPARATOR = ",";\n public static final String EMPTY_STRING = "";\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n \n StringBuilder builder = new StringBuilder();\n Queue<TreeNode> queue = new LinkedList<>();\n queue.offer(root);\n \n while(!queue.isEmpty()) {\n \n TreeNode node = queue.poll();\n \n if(node!=null) {\n builder.append(node.val);\n queue.offer(node.left);\n queue.offer(node.right);\n } else {\n builder.append(EMPTY_STRING);\n }\n \n // append separator\n builder.append(SEPARATOR);\n }\n \n // rmeove last space\n builder.deleteCharAt(builder.length() - 1);\n \n return builder.toString();\n }\n\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n\n String[] values = data.split(SEPARATOR);\n if(values[0].equals(EMPTY_STRING)) {\n return null;\n }\n\n TreeNode root = new TreeNode(Integer.valueOf(values[0]));\n\n Queue<TreeNode> queue = new LinkedList<>();\n queue.offer(root);\n \n int parentIndex=0;\n while(!queue.isEmpty()) {\n \n TreeNode parent = queue.poll();\n\n int leftChildIndex = 2 * parentIndex + 1;\n int rightChildIndex = 2 * parentIndex + 2; \n \n if(leftChildIndex < values.length) {\n if(values[leftChildIndex].equals(EMPTY_STRING)) {\n parent.left = null;\n } else {\n int val = Integer.valueOf(values[leftChildIndex]);\n TreeNode leftChild = new TreeNode(val);\n parent.left = leftChild;\n queue.offer(leftChild);\n }\n }\n\n if(rightChildIndex<values.length) {\n if(values[rightChildIndex].equals(EMPTY_STRING)) {\n parent.right = null;\n } else {\n int val = Integer.valueOf(values[rightChildIndex]);\n TreeNode rightChild = new TreeNode(val);\n parent.right = rightChild;\n queue.offer(rightChild);\n } \n }\n\n parentIndex++; \n }\n \n return root;\n }\n}\n``` | 3 | 0 | [] | 0 |
serialize-and-deserialize-bst | Serialize and Deserialize BST C++ | serialize-and-deserialize-bst-c-by-razva-nhp5 | \nclass Codec {\npublic:\n\n string serialize(TreeNode* root) \n {\n return !root ? " null" : " " + to_string(root->val) + serialize(root->left) + | razvan1403 | NORMAL | 2020-10-10T06:11:19.015890+00:00 | 2020-10-10T06:11:19.015928+00:00 | 80 | false | ```\nclass Codec {\npublic:\n\n string serialize(TreeNode* root) \n {\n return !root ? " null" : " " + to_string(root->val) + serialize(root->left) + serialize(root->right);\n }\n\t\n TreeNode* deserialize(string data) \n {\n istringstream ss(data);\n\t\treturn buildBST(ss);\n }\n \nprivate:\n \n TreeNode* buildBST(istringstream& ss)\n {\n string s;\n ss >> s;\n \n if (s == "null")\n\t\t\treturn NULL;\n \n TreeNode* node = new TreeNode(stoi(s));\n node->left = buildBST(ss);\n node->right = buildBST(ss);\n \n return node;\n }\n};\n``` | 3 | 0 | [] | 0 |
serialize-and-deserialize-bst | [Python] simple recursive solution | python-simple-recursive-solution-by-101l-80e1 | \n ## RC ##\n ## APPROACH : RECURSION ##\n ## Similar to 297. Serialize and Deserialize Binary Tree ##\n\t\t## TIME COMPLEXITY : O(N) ##\n\ | 101leetcode | NORMAL | 2020-06-22T15:19:58.104761+00:00 | 2020-06-22T15:19:58.104804+00:00 | 555 | false | ```\n ## RC ##\n ## APPROACH : RECURSION ##\n ## Similar to 297. Serialize and Deserialize Binary Tree ##\n\t\t## TIME COMPLEXITY : O(N) ##\n\t\t## SPACE COMPLEXITY : O(N) ##\n\nclass Codec:\n\n def serialize(self, root: TreeNode) -> str:\n """Encodes a tree to a single string.\n """\n def dfs(root, string):\n if root is None:\n string += \'None,\'\n else:\n string += str(root.val) + \',\'\n string = dfs(root.left, string)\n string = dfs(root.right, string)\n return string\n return dfs(root, \'\')\n\n def deserialize(self, data: str) -> TreeNode:\n """Decodes your encoded data to tree.\n """\n def dfs(l):\n if(l[0] == "None"):\n l.pop(0)\n return None\n root = TreeNode( l.pop(0) )\n root.left = dfs(l)\n root.right = dfs(l)\n return root\n return dfs( data.split(",")[:-1] )\n``` | 3 | 1 | ['Python', 'Python3'] | 1 |
serialize-and-deserialize-bst | javascript preorder | javascript-preorder-by-abdhalees-txm7 | \n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n\n/**\n * E | abdhalees | NORMAL | 2020-01-29T01:56:46.209438+00:00 | 2020-01-29T01:56:46.209487+00:00 | 351 | false | ```\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n\n/**\n * Encodes a tree to a single string.\n *\n * @param {TreeNode} root\n * @return {string}\n */\nvar serialize = function(root) {\n if(!root) return \'\'\n return "" + root.val + \',\' + serialize(root.left) + \',\' + serialize(root.right)\n};\n\n/**\n * Decodes your encoded data to tree.\n *\n * @param {string} data\n * @return {TreeNode}\n */\nvar deserialize = function(data) {\n const arr = data.split(\',\')\n return helper(arr)\n \n function helper(arr) {\n const val = arr.shift()\n if(!val) return null \n const node = new TreeNode(val)\n node.left = helper(arr)\n node.right = helper(arr)\n return node\n }\n \n \n};\n\n/**\n * Your functions will be called as such:\n * deserialize(serialize(root));\n */\n ``` | 3 | 0 | ['JavaScript'] | 0 |
serialize-and-deserialize-bst | Easy to follow, Python, using queue | easy-to-follow-python-using-queue-by-ale-o8pd | \n def serialize(self, root: TreeNode) -> str:\n """Encodes a tree to a single string.\n """\n if not root: return \'\'\n q = col | alexyalunin | NORMAL | 2020-01-13T21:12:59.637698+00:00 | 2020-01-13T21:12:59.637748+00:00 | 487 | false | ```\n def serialize(self, root: TreeNode) -> str:\n """Encodes a tree to a single string.\n """\n if not root: return \'\'\n q = collections.deque([root])\n res = []\n while q:\n node = q.popleft()\n if node:\n q.append(node.left)\n q.append(node.right)\n res.append(str(node.val))\n else:\n res.append(\'None\')\n return \' \'.join(res)\n \n \n def deserialize(self, data: str) -> TreeNode:\n """Decodes your encoded data to tree.\n """\n if not data: return None\n data_q = collections.deque(data.split(\' \'))\n root = TreeNode(int(data_q.popleft()))\n tree_q = collections.deque([root])\n while tree_q:\n node = tree_q.popleft()\n left = data_q.popleft()\n right = data_q.popleft()\n if left != \'None\':\n left_node = TreeNode(int(left))\n node.left = left_node\n tree_q.append(left_node)\n if right != \'None\':\n right_node = TreeNode(int(right))\n node.right = right_node\n tree_q.append(right_node)\n return root\n``` | 3 | 0 | ['Python'] | 0 |
serialize-and-deserialize-bst | Python PreOrder + Queue solution with comments | python-preorder-queue-solution-with-comm-mrwx | \n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# s | darshil_parikh | NORMAL | 2019-05-02T06:13:34.824563+00:00 | 2019-05-02T06:13:34.824664+00:00 | 401 | false | ```\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Codec:\n\n def serialize(self, root):\n """Encodes a tree to a single string.\n \n :type root: TreeNode\n :rtype: str\n """\n # Pre-Order Traversal of Tree\n # Putting a marker to notify None/null, so we can recognize it during deserialization\n if root == None:\n return \'X,\'\n \n left_subtree = self.serialize(root.left) \n right_subtree = self.serialize(root.right)\n \n # Putting a delimiter on which we can split our string on during deserialization\n return str(root.val) + "," + left_subtree + right_subtree\n \n def deserializeHelper(self, data):\n # If we encounter our marker("X") for None/null node, pop out from our queue(data) and return None\n # Also its our base condition!!!\n if data[0] == "X":\n del data[0]\n return None\n \n # Making a tree node with the front most element in the queue\n new_node = TreeNode(data[0])\n del data[0] # Popping our element from queue\n \n # When we encounter one "X" we move from left subtree to current(new_node) and when we encounter\n # two "X"\'s we are moving to the parent (Just trying to explain the recursion taking place)\n new_node.left = self.deserializeHelper(data) \n new_node.right = self.deserializeHelper(data)\n \n return new_node\n\n def deserialize(self, data):\n """Decodes your encoded data to tree.\n \n :type data: str\n :rtype: TreeNode\n """\n # Splitting our data on the delimeter we used during serialization\n data = data.split(",")\n del data[-1] # Last one will be None/null so omitting it\n return self.deserializeHelper(data)\n \n# Thanks to BackToBackSWE (Youtube Channel) for helping me understand this question better\n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.deserialize(codec.serialize(root))\n``` | 3 | 0 | [] | 1 |
serialize-and-deserialize-bst | A Simple Solution with Only 12 Lines of Code Beats 98% | a-simple-solution-with-only-12-lines-of-qzjgb | This solution utilizes a small array to hold the position of current value, which simplifies the code to the minimum.\n\n\npublic class Codec {\n\n // Encode | lancewang | NORMAL | 2018-07-06T23:54:35.525351+00:00 | 2018-09-12T15:24:52.428666+00:00 | 474 | false | This solution utilizes a small array to hold the position of current value, which simplifies the code to the minimum.\n\n```\npublic class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n if(root == null) return "#";\n \n return root.val + "," + serialize(root.left) + "," + serialize(root.right);\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n String[] values = data.split(",");\n \n return deserialize(values, new int[1]);\n }\n \n private TreeNode deserialize(String[] values, int[] pos){\n if("#".equals(values[pos[0]])){\n pos[0]++;\n return null;\n }\n \n TreeNode cur = new TreeNode(Integer.valueOf(values[pos[0]]));\n pos[0]++;\n \n cur.left = deserialize(values, pos);\n cur.right = deserialize(values, pos);\n \n return cur;\n }\n}\n\n``` | 3 | 0 | [] | 1 |
serialize-and-deserialize-bst | C++ 28ms soluton, Used the same encoding scheme Leetcode uses to serialize/deserialize tree problem I/O | c-28ms-soluton-used-the-same-encoding-sc-y7cu | Encoding scheme\nFor below tree\n\n 2\n / \\\n 1 4\n / \\\n 3 5\n\nAfter serialization\n\n2,1,4,#,#,3,5\n\n#### Implementation\n\n\n/**\n * Def | kaidul | NORMAL | 2016-11-04T13:24:17.183000+00:00 | 2016-11-04T13:24:17.183000+00:00 | 1,512 | false | #### Encoding scheme\nFor below tree\n```\n 2\n / \\\n 1 4\n / \\\n 3 5\n```\nAfter serialization\n```\n2,1,4,#,#,3,5\n```\n#### Implementation\n\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 {\n string getNextNode(string const& data, int& offset) {\n int end = data.find(',', offset);\n if(end == string::npos) {\n end = data.length();\n }\n string sNodeValue = data.substr(offset, end - offset);\n offset = end + 1;\n \n return sNodeValue;\n }\npublic:\n\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n string result = "";\n if(!root) return result;\n queue <TreeNode*> Q;\n Q.push(root);\n result += to_string(root->val);\n result += ',';\n while(!Q.empty()) {\n TreeNode* node = Q.front();\n if(node->left) {\n result += to_string(node->left->val);\n result += ',';\n Q.push(node->left);\n } else {\n result += "#,";\n }\n if(node->right) {\n result += to_string(node->right->val);\n result += ',';\n Q.push(node->right);\n } else {\n result += "#,";\n }\n Q.pop();\n }\n // triming , and # from end\n int i = result.size() - 1;\n for(--i; i >= 0 and result[i] == '#'; i -= 2);\n return result.substr(0, i + 1);\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n TreeNode* root = nullptr;\n if(data.empty()) return root;\n queue<TreeNode*> Q;\n int offset = 0;\n int nodeValue = stoi(getNextNode(data, offset));\n root = new TreeNode(nodeValue);\n Q.push(root);\n while(!Q.empty()) {\n TreeNode* node = Q.front();\n if(offset < data.length()) {\n string sValue = getNextNode(data, offset);\n if(sValue != "#") {\n int leftNodeValue = stoi(sValue);\n node->left = new TreeNode(leftNodeValue);\n Q.push(node->left); \n }\n }\n if(offset < data.length()) {\n string sValue = getNextNode(data, offset);\n if(sValue != "#") {\n int rightNodeValue = stoi(sValue);\n node->right = new TreeNode(rightNodeValue);\n Q.push(node->right); \n }\n }\n Q.pop();\n }\n return root;\n }\n};\n\n// Your Codec object will be instantiated and called as such:\n// Codec codec;\n// codec.deserialize(codec.serialize(root));\n``` | 3 | 0 | [] | 0 |
serialize-and-deserialize-bst | C# - pre-order serialize - very compact, no commas, no null, no separators | c-pre-order-serialize-very-compact-no-co-2ohv | Here is the idea. Each node can be serialized with a prefix char and and Abs value. The prefix char acts as the separator and denotes the sign of the value an | jdrogin | NORMAL | 2016-11-05T20:43:27.895000+00:00 | 2016-11-05T20:43:27.895000+00:00 | 980 | false | Here is the idea. Each node can be serialized with a prefix char and and Abs value. The prefix char acts as the separator and denotes the sign of the value and if the value has a left or right or both or is a leaf.\n\nI use this code but any similar codes could be used\n```\n'x' = leaf\n'l' = left node only\n'r' = right node only\n'f' = full or both left and right\n```\n\nif the value is negative I take the capitalization of the prefix\n```\n'X' = leaf and negative value\n'L' = left node only and negative value\n'R' = right node only and negative value\n'F' = full or both left and right and negative value\n```\n\nFor example:\nA node with value "2" and a left node only\n```\nl2\n```\nA node with a value of "-1234" which is a leaf\n```\nX1234\n```\n\nThese could be strung together to form a root "2" with left node leaf "-1234"\n```\nl2X1234\n```\n\nThis could be further optimized by choosing codes in the upper alphabet and serializing numbers in hex. And of course you could compact this even further by using a binary system and encoding as integers. But I thought the main trick here of using the prefix was the piece I wanted to share.\n\n```\n \n public class Codec\n {\n // Encodes a tree to a single string.\n public string serialize(TreeNode root)\n {\n StringBuilder sb = new StringBuilder();\n BuildSerialize(root, sb);\n return sb.ToString();\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(string data)\n {\n NodeIter nodeIter = new NodeIter(data);\n TreeNode root = this.BuildDeserialize(nodeIter);\n return root;\n }\n\n private void BuildSerialize(TreeNode node, StringBuilder sb)\n {\n // pre-order\n if (node == null) return;\n sb.Append(SerializeNode(node));\n BuildSerialize(node.left, sb);\n BuildSerialize(node.right, sb);\n }\n\n private string SerializeNode(TreeNode node)\n {\n if (node == null) return "";\n\n char c = '$';\n if (node.left != null && node.right != null) c = 'f'; // full - both left and right\n else if (node.left != null) c = 'l'; // left only\n else if (node.right != null) c = 'r'; // right only\n else c = 'x'; // leaf\n\n if (node.val < 0) c = Char.ToUpper(c); // negative value identified by upper case\n\n return c.ToString() + Math.Abs(node.val).ToString();\n }\n\n private TreeNode BuildDeserialize(NodeIter nodeIter)\n {\n TreeNode node = nodeIter.Next();\n if (node == null) return node;\n if (node.left != null)\n {\n node.left = BuildDeserialize(nodeIter);\n }\n if (node.right != null)\n {\n node.right = BuildDeserialize(nodeIter);\n }\n return node;\n }\n }\n\n public class NodeIter\n {\n private string str = null;\n private int pos = 0;\n public NodeIter(string s)\n {\n this.str = s == null ? "" : s;\n }\n\n public TreeNode Next()\n {\n TreeNode node = null;\n if (this.pos < this.str.Length)\n {\n node = new TreeNode(1);\n char c = this.str[this.pos];\n if (Char.IsUpper(c)) node.val = -1;\n switch (Char.ToLower(c))\n {\n case 'x': break;\n case 'l': node.left = new TreeNode(0); break;\n case 'r': node.right = new TreeNode(0); break;\n case 'f': node.left = new TreeNode(0); node.right = new TreeNode(0); break;\n default: break;\n }\n\n this.pos++;\n int val = 0;\n while (this.pos < this.str.Length && Char.IsDigit(this.str[this.pos]))\n {\n val = val * 10 + this.str[this.pos] - '0';\n this.pos++;\n }\n node.val *= val;\n }\n return node;\n }\n }\n``` | 3 | 0 | [] | 0 |
serialize-and-deserialize-bst | Easy BFS JAVA | easy-bfs-java-by-jonkugolu-pfig | ```\n// Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n Queue q=new LinkedList();\n StringBuilder s=new StringB | jonkugolu | NORMAL | 2016-12-18T00:06:18.885000+00:00 | 2016-12-18T00:06:18.885000+00:00 | 923 | false | ```\n// Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n Queue<TreeNode> q=new LinkedList<TreeNode>();\n StringBuilder s=new StringBuilder();\n if(root==null)\n return "*-";\n q.add(root);\n while(!q.isEmpty()){\n TreeNode temp=q.remove();\n if(temp==null)\n s.append("*-");\n else{\n s.append(temp.val+"-");\n q.add(temp.left);\n q.add(temp.right);\n }\n }\n \n return s.toString();\n }\n\n// Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n String[] val=data.split("-");\n \n if(val.length==0)\n return null;\n if(val[0].equals("*"))\n return null;\n Queue<TreeNode> q=new LinkedList<TreeNode>();\n TreeNode root=new TreeNode(Integer.parseInt(val[0]));\n q.add(root);\n for(int i=1;i<val.length;i=i+2){\n TreeNode Node=q.remove();\n if(!val[i].equals("*")){\n Node.left=new TreeNode(Integer.parseInt(val[i]));\n q.add(Node.left);\n }\n if(i+1<val.length && !val[i+1].equals("*")){\n Node.right=new TreeNode(Integer.parseInt(val[i+1]));\n q.add(Node.right);\n }\n }\n \n return root;\n } | 3 | 0 | [] | 0 |
serialize-and-deserialize-bst | construct BST using preorder traversal. | construct-bst-using-preorder-traversal-b-1opt | At first I thought this was the same as serialization/deserialization of a generic BT. Since the problem suggests minimal codec size and avoid using any externa | shallpion | NORMAL | 2016-11-01T03:51:39.141000+00:00 | 2016-11-01T03:51:39.141000+00:00 | 2,205 | false | At first I thought this was the same as serialization/deserialization of a generic BT. Since the problem suggests minimal codec size and avoid using any external variable/function/etc I chose preorder and using stack to avoid using aux function. It can be made a little easier if using recursion I suppose. Also I think postorder works as well.\n\n\n\n class Codec {\n public:\n \n \t// Encodes a tree to a single string.\n \tstring serialize(TreeNode* root) {\n \t\t// preorder traversal\n \t\tstring ret;\n \t\tif(!root) return ret;\n \t\t\n \t\tstack<TreeNode*> stk;\n \t\tstk.push(root);\n \t\twhile(!stk.empty()){\n \t\t\tTreeNode *r = stk.top();\n \t\t\tstk.pop();\n \t\t\tret += to_string(r->val) + ",";\n \t\t\tif(r->right) stk.push(r->right);\n \t\t\tif(r->left) stk.push(r->left);\n \n \t\t}\n \t\treturn ret.substr(0, ret.size()-1);\n \t}\n \n \t// Decodes your encoded data to tre.\n \tTreeNode* deserialize(string data) {\n \t if(data.size() == 0) return nullptr;\n \t \n \t\tint id = 0;\n \t\t// take root at first\n \t\tint r = id;\n \t\twhile(isdigit(data[r])) r++;\n \t\tint v = stoi(data.substr(id, r-id));\n \t\tid = r+1;\n \n \t\tTreeNode *root = new TreeNode(v);\n \t\tstack<TreeNode*> stk;\n \t\tstk.push(root);\n \n \t\twhile(id < (int) data.size()) {\n \t\t\tint r = id;\n \t\t\twhile(isdigit(data[r]))\tr++;\n \t\t\tint v = stoi(data.substr(id, r - id));\n \t\t\tid = r + 1;\n \n \t\t\tTreeNode *node = nullptr;\n \t\t\twhile(!stk.empty() && v > stk.top()->val) {\n \t\t\t\tnode = stk.top();\n \t\t\t\tstk.pop();\n \t\t\t}\n \t\t\tif(node) {\n \t\t\t\tnode->right = new TreeNode(v);\n \t\t\t\tstk.push(node->right);\n \t\t\t} else {\n \t\t\t\tstk.top()->left = new TreeNode(v);\n \t\t\t\tstk.push(stk.top()->left);\n \t\t\t}\n \t\t}\n \n \t\treturn root;\n \t}\n \t// for debug\n \tvoid f(TreeNode *root) {\n \t\tif(!root) return;\n \t\tf(root->left);\n \t\tcout << root->val << ", ";\n \t\tf(root->right);\n \t}\n }; | 3 | 0 | [] | 1 |
serialize-and-deserialize-bst | Python solution serializing as Preorder list | python-solution-serializing-as-preorder-v7afd | The remarkable difference from serialize/deserialize Binary Tree ( https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ ) is, BST can be constru | redtree1112 | NORMAL | 2017-07-03T08:22:56.445000+00:00 | 2017-07-03T08:22:56.445000+00:00 | 808 | false | The remarkable difference from serialize/deserialize Binary Tree ( https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ ) is, **BST can be constructed just from its preorder array** while a general binary tree requires both [in-order and and pre-order](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/#/description ) or [in-order and post-order](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/#/description).\n\nSo for serializing BST, just perform a pre-order traversal and stringify the result array.\nDeserialization can be also done in the same manner as:\nhttp://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversal-set-2/\n\n```\nclass Codec:\n def serialize(self, root):\n if not root:\n return "none"\n cur = root\n \n res = ""\n stack = []\n while cur:\n res += str(cur.val) + ","\n \n if cur.right:\n stack.append(cur)\n \n if cur.left:\n cur = cur.left\n elif not stack:\n break\n else:\n cur = stack.pop()\n cur = cur.right\n return res[:-1] # remove the last ","\n \n def deserialize(self, data):\n if data == "none":\n return None\n vals = data.split(",")\n root = TreeNode(int(vals[0]))\n cur = root\n \n stack = []\n for i in range(1, len(vals)):\n val = int(vals[i])\n \n if val < cur.val:\n cur.left = TreeNode(val)\n stack.append(cur)\n cur = cur.left\n else:\n while stack and cur.val < val:\n if stack[-1].val < val:\n cur = stack.pop()\n else:\n break\n cur.right = TreeNode(val)\n cur = cur.right\n return root\n \n``` | 3 | 0 | ['Python'] | 1 |
serialize-and-deserialize-bst | C++ Truly O(n) solution using BFS with explanation | c-truly-on-solution-using-bfs-with-expla-ry3l | Can also be used to optimally solve https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/\n\nUnlike many solutions posted, this is a | Ningck | NORMAL | 2024-11-12T22:29:18.533081+00:00 | 2024-11-12T22:29:18.533117+00:00 | 175 | false | Can also be used to optimally solve https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/\n\nUnlike many solutions posted, this is a truly O(n) solution. Basically we are seralize and deserializing using BFS or level-by-level traversal.\n\n# Code\n```cpp []\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 // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n if (root == nullptr) return "";\n string ans = "";\n queue<TreeNode*> bfsQueue;\n bfsQueue.push(root);\n while (!bfsQueue.empty()) {\n TreeNode* curr = bfsQueue.front();\n bfsQueue.pop();\n if (curr == nullptr) ans += "# ";\n else {\n ans += std::to_string(curr->val) + " ";\n bfsQueue.push(curr->left);\n bfsQueue.push(curr->right);\n }\n }\n return ans;\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n vector<string> vals;\n string curr = "";\n for (char v: data) {\n if (v == \' \') {\n if (curr != "") {\n vals.push_back(curr);\n curr = "";\n }\n } else {\n curr += v;\n }\n }\n if (vals.empty()) return nullptr;\n\n TreeNode* root = new TreeNode(std::stoi(vals[0]));\n queue<TreeNode*> bfsQueue;\n bfsQueue.push(root);\n int index = 1;\n while (!bfsQueue.empty()) {\n TreeNode* curr = bfsQueue.front();\n bfsQueue.pop();\n\n // process left\n string left = vals[index];\n ++index;\n if (left == "#") {\n curr->left = nullptr;\n } else {\n TreeNode* newNode = new TreeNode(std::stoi(left));\n curr->left = newNode;\n bfsQueue.push(newNode);\n }\n\n // process right\n string right = vals[index];\n ++index;\n if (right == "#") {\n curr->right = nullptr;\n } else {\n TreeNode* newNode = new TreeNode(std::stoi(right));\n curr->right = newNode;\n bfsQueue.push(newNode);\n }\n }\n\n return 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``` | 2 | 0 | ['C++'] | 0 |
serialize-and-deserialize-bst | easy solution :) | easy-solution-by-swati_123-a-qmag | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Swati_123-a | NORMAL | 2024-07-17T01:06:16.556058+00:00 | 2024-07-17T01:06:16.556079+00:00 | 345 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\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\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n if(!root) return "null,";\n return to_string(root->val)+ "," +serialize(root->left) +serialize(root->right); \n }\n\n int i=0;\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n if(i>=data.size())return nullptr;\n\n string t="";\n while(data[i]!=\',\') t+=data[i++];\n i++;\n\n if(t=="null") return nullptr;\n TreeNode* root=new TreeNode(stoi(t));\n root->left=deserialize(data);\n root->right=deserialize(data);\n return 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``` | 2 | 0 | ['C++'] | 0 |
serialize-and-deserialize-bst | 🌺26. Pre Order Traversal || 2 Solutions|| Short & Sweet Code || C++ Code Reference | 26-pre-order-traversal-2-solutions-short-g557 | Intuition\n1. By Using Any Traversal Technique PreOrder, PostOrder Or Level Order :\n - Convert Tree To String \n - Convert Back String To Tree \n# Approa | Amanzm00 | NORMAL | 2024-07-10T04:04:51.897390+00:00 | 2024-07-10T04:31:18.303233+00:00 | 252 | false | # Intuition\n1. By Using Any Traversal Technique PreOrder, PostOrder Or Level Order :\n - Convert Tree To String \n - Convert Back String To Tree \n# Approach\n1. I Traverse PreOrder Wise To Serialize The Tree Using `Preorder` Function !\n2. In Deserialization I Parse The String & Store Node Values In Vector \n3. Then I Simply Convert It To Tree !! Using `Convert` Function !!\n\n> Solution 2 Is Similar , But Concised !\n\n# Code\n```cpp [Solution 1]\nclass Codec {\n // Binary Tree Can Be Constructed From PreOrder Traversal If It Is Full Binary Tree\n // So Serialize Such That If Child Are null You Include It In PreOrder Traversal \npublic:\n\n // Serialize : \n\n string S="";\n string serialize(TreeNode* a) {\n Preorder(a);\n return S;\n }\n void Preorder(TreeNode* a){\n if(!a) { S+="null,"; return; }\n\n S=S+to_string(a->val)+",";\n Preorder(a->left);\n Preorder(a->right);\n }\n\n // Deserialize : \n\n vector<string> V;\n TreeNode* deserialize(string s) {\n string t="";\n for(auto & i : s)\n if(i==\',\') { V.push_back(t); t=""; }\n else t+=i;\n\n int i=0;\n return Convert(i); \n }\n TreeNode* Convert(int& i){\n if(i>=V.size()||V[i]=="null"){i++;return nullptr;}\n\n TreeNode* a=new TreeNode(stoi(V[i++]));\n a->left=Convert(i);\n a->right=Convert(i);\n return a;\n }\n};\n```\n\n```cpp [Solution 2 ]\n\n string serialize(TreeNode* a) {\n if(!a) return "null,";\n return to_string(a->val)+ "," +serialize(a->left)+serialize(a->right); \n }\n\n int i=0;\n TreeNode* deserialize(string s) { \n if(i>=s.size())return nullptr;\n\n string t="";\n while(s[i]!=\',\') t+=s[i++];\n i++;\n\n if(t=="null") return nullptr;\n TreeNode* a=new TreeNode(stoi(t));\n a->left=deserialize(s);\n a->right=deserialize(s);\n return a;\n }\n};\n\n```\n\n---\n# *Guy\'s Upvote Pleasee !!* \n\n\n# ***(\u02E3\u203F\u02E3 \u035C)***\n\n\n | 2 | 0 | ['String', 'Tree', 'Depth-First Search', 'Breadth-First Search', 'Design', 'Binary Search Tree', 'Recursion', 'C++'] | 0 |
serialize-and-deserialize-bst | ostringstream || istringstream | ostringstream-istringstream-by-ayushrakw-lsp3 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ayushrakwal94 | NORMAL | 2024-01-12T13:26:52.107170+00:00 | 2024-01-12T13:26:52.107208+00:00 | 114 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Codec {\npublic:\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n ostringstream ss;\n Helper1(root, ss);\n return ss.str();\n }\n\n void Helper1(TreeNode* root, ostringstream& ss) {\n if (root == NULL) {\n ss << "# ";\n return;\n }\n ss << root->val << " ";\n Helper1(root->left, ss);\n Helper1(root->right, ss);\n }\n\n // Decodes your encoded data to tree.\n int i;\n\n TreeNode* deserialize(string data) {\n istringstream ss(data);\n vector<string>ans;\n string an;\n\n while (ss >> an) {\n ans.push_back(an);\n }\n\n i = 0;\n return Helper2(ans);\n }\n\n TreeNode* Helper2(vector<string>& ans) {\n if (ans[i] == "#") {\n i++;\n return NULL;\n }\n TreeNode* root = new TreeNode(stoi(ans[i]));\n i++;\n root->left = Helper2(ans);\n root->right = Helper2(ans);\n return root;\n }\n};\n\n``` | 2 | 0 | ['C++'] | 0 |
serialize-and-deserialize-bst | 3-line code only || 100 % faster java solution | 3-line-code-only-100-faster-java-solutio-4obw | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | alokranjanjha10 | NORMAL | 2023-09-11T14:16:54.676175+00:00 | 2023-09-11T14:16:54.676201+00:00 | 348 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\npublic class Codec {\n\n // Encodes a tree to a single string.\n static TreeNode res;\n public String serialize(TreeNode root) {\n res=root;\n return "";\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n return res;\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``` | 2 | 1 | ['Java'] | 2 |
serialize-and-deserialize-bst | 3 line || 0 ms || 100 % faster java solution | 3-line-0-ms-100-faster-java-solution-by-wa9xq | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | bikramghoshal6337 | NORMAL | 2023-09-11T06:57:39.768143+00:00 | 2023-09-11T06:57:39.768177+00:00 | 184 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\npublic class Codec {\n\n static TreeNode res;\n public String serialize(TreeNode root) {\n res = root;\n return "";\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n return res;\n }\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``` | 2 | 1 | ['Java'] | 1 |
serialize-and-deserialize-bst | ✅✔️Easy Implementation using level order Traversal || C++ Solution ✈️✈️✈️✈️✈️ | easy-implementation-using-level-order-tr-24ui | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ajay_1134 | NORMAL | 2023-07-01T13:34:26.691524+00:00 | 2023-07-01T13:34:26.691554+00:00 | 327 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\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\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n if(!root) return "";\n string ans = to_string(root->val) + ",";\n queue<TreeNode*>q;\n q.push(root);\n while(!q.empty()){\n root = q.front();\n q.pop();\n if(root->left){\n ans += (to_string(root->left->val) + ",");\n q.push(root->left);\n } \n else ans += ("#,");\n if(root->right){\n ans += (to_string(root->right->val) + ",");\n q.push(root->right);\n }\n else ans += ("#,"); \n }\n return ans;\n }\n\n int num(string &data,int &idx){\n string s = "";\n while(idx < data.length() && data[idx] != \',\'){\n s += data[idx];\n idx++;\n }\n idx++;\n if(s == "#") return -1;\n return stoi(s);\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n if(data.empty()) return NULL;\n int idx = 0;\n TreeNode* root = new TreeNode(num(data,idx));\n queue<TreeNode*>q;\n q.push(root);\n while(idx < data.length() && !q.empty()){\n TreeNode* node = q.front(); q.pop();\n int left = num(data,idx);\n int right = num(data,idx);\n node->left = (left == -1) ? NULL : new TreeNode(left);\n node->right = (right == -1) ? NULL : new TreeNode(right);\n if(node->left) q.push(node->left);\n if(node->right) q.push(node->right);\n }\n return 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``` | 2 | 0 | ['Tree', 'Breadth-First Search', 'Binary Search Tree', 'Binary Tree', 'C++'] | 0 |
serialize-and-deserialize-bst | C++ || Serialize & Deserialize || Easy approach | c-serialize-deserialize-easy-approach-by-k3i7 | Here is my c++ code for this problem.\n\n# Complexity\n- Time complexity:O(n)\n\n- Space complexity:O(n)\n\n# Code\n\n/**\n * Definition for a binary tree node. | mrigank_2003 | NORMAL | 2023-03-16T06:01:53.686195+00:00 | 2023-03-16T06:01:53.686226+00:00 | 1,601 | false | Here is my c++ code for this problem.\n\n# Complexity\n- Time complexity:$$O(n)$$\n\n- Space complexity:$$O(n)$$\n\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\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n string s="";\n if(!root){\n return s;\n }\n queue<TreeNode*>q;\n q.push(root);\n while(!q.empty()){\n TreeNode* node=q.front();\n q.pop();\n if(!node){\n s+="#,";\n }\n else{\n s+=to_string(node->val)+\',\';\n q.push(node->left);\n q.push(node->right);\n }\n }\n return s;\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n if(data.empty()){return NULL;}\n string s="";\n stringstream x(data);\n getline(x, s, \',\');\n TreeNode* root=new TreeNode(stoi(s));\n queue<TreeNode*>q;\n q.push(root);\n while(!q.empty()){\n TreeNode* node=q.front();\n q.pop();\n getline(x, s, \',\');\n if(s=="#"){\n node->left=NULL;\n }\n else{\n TreeNode* lft=new TreeNode(stoi(s));\n node->left=lft;\n q.push(lft);\n }\n getline(x, s, \',\');\n if(s=="#"){\n node->right=NULL;\n }\n else{\n TreeNode* rgt=new TreeNode(stoi(s));\n node->right=rgt;\n q.push(rgt);\n }\n }\n return 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``` | 2 | 0 | ['String', 'Binary Search Tree', 'Binary Tree', 'C++'] | 0 |
serialize-and-deserialize-bst | 449: Time 91.2%, Solution with step by step explanation | 449-time-912-solution-with-step-by-step-buwq5 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nFor the serialize function:\n\n1. If the given root is None, return an em | Marlen09 | NORMAL | 2023-03-09T04:59:39.043422+00:00 | 2023-03-09T04:59:39.043470+00:00 | 2,270 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nFor the serialize function:\n\n1. If the given root is None, return an empty string.\n2. Create an empty stack and push the root node to it.\n3. Create an empty string called serialized.\n4. While the stack is not empty, pop a node from the stack.\n5. If the node is None, append "$," to the serialized string.\n6. Otherwise, append the node\'s value followed by "," to the serialized string.\n7. Push the node\'s right child to the stack (if it exists).\n8. Push the node\'s left child to the stack (if it exists).\n9. Return the serialized string without the last comma.\n\nFor the deserialize function:\n\n1. If the given data string is empty, return None.\n2. Split the data string by comma and create a deque called queue from the resulting list.\n3. Call the _deserialize function with queue as the argument and return its result.\n\nFor the _deserialize function:\n\n1. Pop the leftmost value from the queue and store it in a variable called value.\n2. If value is "$", return None.\n3. Create a new TreeNode with the integer value of value.\n4. Set the node\'s left child to the result of calling _deserialize recursively with queue.\n5. Set the node\'s right child to the result of calling _deserialize recursively with queue.\n6. Return the node.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Codec:\n def serialize(self, root: Optional[TreeNode]) -> str:\n """Encodes a tree to a single string."""\n if not root:\n return ""\n stack = [root]\n serialized = ""\n while stack:\n node = stack.pop()\n if not node:\n serialized += "$,"\n else:\n serialized += str(node.val) + ","\n stack.append(node.right)\n stack.append(node.left)\n return serialized[:-1]\n\n def deserialize(self, data: str) -> Optional[TreeNode]:\n """Decodes your encoded data to tree."""\n if not data:\n return None\n values = data.split(",")\n queue = deque(values)\n return self._deserialize(queue)\n\n def _deserialize(self, queue: Deque[str]) -> Optional[TreeNode]:\n value = queue.popleft()\n if value == "$":\n return None\n node = TreeNode(int(value))\n node.left = self._deserialize(queue)\n node.right = self._deserialize(queue)\n return node\n``` | 2 | 0 | ['String', 'Tree', 'Depth-First Search', 'Python', 'Python3'] | 1 |
serialize-and-deserialize-bst | Python solution | python-solution-by-obose-hrhy | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is asking to implement a serialization and deserialization method for a bin | Obose | NORMAL | 2023-01-14T20:20:35.112362+00:00 | 2023-01-14T20:20:35.112390+00:00 | 810 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is asking to implement a serialization and deserialization method for a binary tree. The serialization method should take a binary tree and convert it into a string format, while the deserialization method should take the string format and convert it back into a binary tree.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe serialization method can be done by doing a breadth-first traversal of the tree and appending the values of the nodes to a list. If a node is None, append "null" to the list. After the traversal, join the list into a string using "," as the delimiter.\n\nThe deserialization method can be done by splitting the string into a list using "," as the delimiter. Create the root node using the first element in the list and append it to a queue. Then, for each element in the list, starting from the second element, check if the element is "null" or not. If it is not "null", create a new node with that value and append it to the left or right of the current node in the queue, depending on whether it is the left or right child. Append the new node to the queue as well. Repeat this process until all elements in the list have been processed.\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Codec:\n\n def serialize(self, root: Optional[TreeNode]) -> str:\n """Encodes a tree to a single string.\n """\n if not root:\n return ""\n queue = [root]\n output = []\n while queue:\n current = queue.pop(0)\n if current:\n output.append(str(current.val))\n queue.append(current.left)\n queue.append(current.right)\n else:\n output.append("null")\n return ",".join(output)\n \n\n def deserialize(self, data: str) -> Optional[TreeNode]:\n """Decodes your encoded data to tree.\n """\n if not data:\n return None\n data = data.split(",")\n root = TreeNode(int(data[0]))\n queue = [root]\n i = 1\n while queue:\n current = queue.pop(0)\n if data[i] != "null":\n current.left = TreeNode(int(data[i]))\n queue.append(current.left)\n i += 1\n if data[i] != "null":\n current.right = TreeNode(int(data[i]))\n queue.append(current.right)\n i += 1\n return root\n\n# Your Codec object will be instantiated and called as such:\n# Your Codec object will be instantiated and called as such:\n# ser = Codec()\n# deser = Codec()\n# tree = ser.serialize(root)\n# ans = deser.deserialize(tree)\n# return ans\n``` | 2 | 0 | ['Python3'] | 0 |
serialize-and-deserialize-bst | Python : Upper/Lower Approach [Preorder DFS] ✅ | python-upperlower-approach-preorder-dfs-aittj | \nclass Codec:\n\n def serialize(self, root: Optional[TreeNode]) -> str:\n self.ans = []\n \n def dfs(node):\n if not node: r | khacker | NORMAL | 2022-09-30T06:09:21.544147+00:00 | 2022-09-30T06:09:21.544190+00:00 | 88 | false | ```\nclass Codec:\n\n def serialize(self, root: Optional[TreeNode]) -> str:\n self.ans = []\n \n def dfs(node):\n if not node: return\n self.ans.append(str(node.val))\n dfs(node.left)\n dfs(node.right)\n \n dfs(root)\n return ",".join(self.ans)\n \n\n def deserialize(self, data: str) -> Optional[TreeNode]:\n if not data: return None\n ans = [int(d) for d in data.split(",")]\n \n \n def dfs(ans, l, u):\n if not ans: return None\n if not l <= ans[0] <= u : return None\n \n node = ans.pop(0) #O(n)\n root = TreeNode(node)\n \n root.left = dfs(ans, l, root.val)\n root.right = dfs(ans, root.val, u)\n \n return root\n return dfs(ans, -float(\'inf\'), float(\'inf\'))\n```\n\nExplaination : After 13 October 2022\nhttps://youtu.be/01f4F9HOb5k\n | 2 | 0 | ['Depth-First Search', 'Python', 'Python3'] | 1 |
serialize-and-deserialize-bst | Cringiest solution || 0ms || 100% Faster solution || using static | cringiest-solution-0ms-100-faster-soluti-95g7 | \npublic class Codec {\n static TreeNode node;\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n node = root; | Lil_ToeTurtle | NORMAL | 2022-08-11T15:39:59.275408+00:00 | 2022-08-11T15:39:59.275451+00:00 | 485 | false | ```\npublic class Codec {\n static TreeNode node;\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n node = root;\n return "";\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n return node;\n }\n}\n\n``` | 2 | 1 | ['Java'] | 4 |
serialize-and-deserialize-bst | Java simple preorder solution | java-simple-preorder-solution-by-1605448-9309 | \npublic class Codec {\n\n // Encodes a tree to a single string.\n public void preorder(TreeNode root, StringBuilder sb) {\n if (root == null) {\n | 1605448777 | NORMAL | 2022-07-08T09:58:14.409481+00:00 | 2022-07-08T09:58:14.409523+00:00 | 686 | false | ```\npublic class Codec {\n\n // Encodes a tree to a single string.\n public void preorder(TreeNode root, StringBuilder sb) {\n if (root == null) {\n sb.append("n" + "/");\n return;\n }\n sb.append(root.val + "/");\n preorder(root.left, sb);\n preorder(root.right, sb);\n }\n\n public String serialize(TreeNode root) {\n StringBuilder sb = new StringBuilder("");\n preorder(root, sb);\n return sb.toString();\n }\n\n // Decodes your encoded data to tree.\n public TreeNode constructTree(String preorder[], int index[], int end) {\n if (index[0] > end) return null;\n if (preorder[index[0]].equals("n")) {\n index[0] += 1;\n return null;\n }\n TreeNode root = new TreeNode(Integer.parseInt(preorder[index[0]]));\n index[0] += 1;\n root.left = constructTree(preorder, index, end);\n root.right = constructTree(preorder, index, end);\n return root;\n }\n\n public TreeNode deserialize(String data) {\n String preorder[] = data.split("/");\n TreeNode root = constructTree(preorder, new int[1], preorder.length - 1);\n return root;\n }\n}\n``` | 2 | 0 | ['Depth-First Search', 'Binary Search Tree', 'Java'] | 0 |
serialize-and-deserialize-bst | Java Level Order Traversal | Readable Code | java-level-order-traversal-readable-code-wnt0 | \npublic class Codec {\n /**\n * Traverses binary tree in level order \n * Stores node values in string(comma separated)\n */\n private String | priyajitbera | NORMAL | 2022-06-26T19:26:13.685956+00:00 | 2022-06-26T19:26:13.685990+00:00 | 551 | false | ```\npublic class Codec {\n /**\n * Traverses binary tree in level order \n * Stores node values in string(comma separated)\n */\n private String levelOrderTrav(TreeNode root){\n StringBuilder sb = new StringBuilder();\n Queue<TreeNode> que = new LinkedList<>();\n que.add(root);\n TreeNode itr = null;\n while(que.size()>0){\n itr = que.remove();\n if(itr!=null) {\n sb.append(itr.val+",");\n que.add(itr.left);\n que.add(itr.right);\n }\n else sb.append("n,");\n }\n return sb.substring(0, sb.length()-1).toString();\n }\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n return levelOrderTrav(root);\n }\n /**\n * Contructs Binary Tree from leverl order traversalcomma separated string)\n */\n private TreeNode constructBstFromLevelOrderTrav(String data){\n String[] nodeValues = data.split(",");\n if(nodeValues[0].equals("n")) return null; //zero nodes\n Queue<TreeNode> que = new LinkedList<>();\n TreeNode root = new TreeNode(Integer.parseInt(nodeValues[0]));\n que.add(root);\n TreeNode itr = null;\n int indx = 1;\n while(que.size()>0){\n itr = que.remove();\n String valL = nodeValues[indx++];\n String valR = nodeValues[indx++];\n if(!valL.equals("n")){\n itr.left = new TreeNode(Integer.parseInt(valL));\n que.add(itr.left);\n }\n if(!valR.equals("n")){\n itr.right = new TreeNode(Integer.parseInt(valR));\n que.add(itr.right);\n }\n }\n return root;\n }\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n return constructBstFromLevelOrderTrav(data);\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
serialize-and-deserialize-bst | C++ simple level-order traversal | c-simple-level-order-traversal-by-mayank-xho6 | \n // Encodes a tree to a single string.\n string serialize(TreeNode root) {\n if(root==NULL)\n return "";\n string s="";\n | mayankks0010 | NORMAL | 2022-01-21T13:32:57.203669+00:00 | 2022-01-21T13:32:57.203724+00:00 | 164 | false | \n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n if(root==NULL)\n return "";\n string s="";\n \n queue<TreeNode*> q;\n q.push(root);\n while(!q.empty())\n {\n TreeNode* temp=q.front();\n q.pop();\n \n if(temp==NULL)\n {\n s.append("#,");\n }\n else\n {\n s.append(to_string(temp->val)+\',\');\n }\n \n if(temp!=NULL)\n {\n q.push(temp->left);\n q.push(temp->right);\n }\n }\n\n return s;\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n if(data.length()==0)\n return NULL;\n \n stringstream s(data);\n string str;\n getline(s,str,\',\');\n TreeNode* root=new TreeNode(stoi(str));\n queue<TreeNode*> q;\n q.push(root);\n \n while(!q.empty())\n {\n TreeNode* temp=q.front();\n q.pop();\n \n getline(s,str,\',\');\n if(str=="#")\n {\n temp->left=NULL;\n }\n else\n {\n TreeNode* leftNode=new TreeNode(stoi(str));\n temp->left=leftNode;\n q.push(leftNode);\n }\n \n getline(s,str,\',\');\n if(str=="#")\n {\n temp->right=NULL;\n }\n else\n {\n TreeNode* rightNode=new TreeNode(stoi(str));\n temp->right=rightNode;\n q.push(rightNode);\n }\n }\n \n return root;\n }\n\n | 2 | 0 | ['String', 'Queue'] | 1 |
serialize-and-deserialize-bst | Beat 99% 2ms No delimiter(e.g. comma), no stack/queue. Just turn val into char | beat-99-2ms-no-delimitereg-comma-no-stac-q3db | \npublic class Codec {\n\n /*\n max node.val is 10000, less than 6xxxx(max value of char) \n So just turn node.val into char.\n Serialize with pre | cstsangac | NORMAL | 2021-08-13T08:33:10.261815+00:00 | 2021-08-13T08:35:32.536015+00:00 | 281 | false | ```\npublic class Codec {\n\n /*\n max node.val is 10000, less than 6xxxx(max value of char) \n So just turn node.val into char.\n Serialize with preorder (parent > left > right)\n */\n public String serialize(TreeNode root) {\n StringBuilder sb = new StringBuilder();\n helper_serialize(sb, root);\n return sb.toString();\n }\n \n private void helper_serialize(StringBuilder sb, TreeNode root) {\n if (root == null) \n return;\n sb.append((char)(root.val + \'0\'));\n helper_serialize(sb, root.left);\n helper_serialize(sb, root.right);\n }\n\n /*\n it\'s BST, so it\'s already in proper order as long as you add the node in order.\n */\n public TreeNode deserialize(String data) {\n TreeNode root = null;\n for(char c : data.toCharArray()) {\n root = add(root, c - \'0\');\n }\n return root;\n }\n private TreeNode add(TreeNode root, int val) {\n if (root == null)\n return new TreeNode(val);\n \n if (val < root.val) {\n root.left = add(root.left, val);\n } else {\n root.right = add(root.right, val);\n }\n return root;\n }\n}\n```\n\n\nFYI what char looks like when int is above 9:\n\n```\nint: 5 char: 5\nint: 6 char: 6\nint: 7 char: 7\nint: 8 char: 8\nint: 9 char: 9\nint: 10 char: :\nint: 11 char: ;\nint: 12 char: <\nint: 13 char: =\nint: 14 char: >\nint: 15 char: ?\n``` | 2 | 1 | ['Java'] | 0 |
serialize-and-deserialize-bst | C++ | Queue and Preorder | c-queue-and-preorder-by-steffi_keran-8bmu | \nclass Codec {\npublic:\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n if(!root) return "x,";\n string l=s | steffi_keran | NORMAL | 2021-08-08T13:12:50.909584+00:00 | 2021-08-08T13:12:50.909625+00:00 | 268 | false | ```\nclass Codec {\npublic:\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n if(!root) return "x,";\n string l=serialize(root->left);\n string r=serialize(root->right);\n return to_string(root->val)+","+l+r;\n }\n \n TreeNode* deserializeHelper(queue<string>& q) {\n string ch=q.front();\n q.pop();\n if(ch=="x") return NULL;\n TreeNode* root=new TreeNode(stoi(ch));\n root->left=deserializeHelper(q);\n root->right=deserializeHelper(q);\n return root; \n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n stringstream ss(data);\n queue<string> q;\n cout << data<< endl;\n while (ss.good()) {\n string str;\n getline(ss, str,\',\');\n q.push(str);\n }\n return deserializeHelper(q);\n }\n};\n``` | 2 | 0 | ['Queue', 'C'] | 0 |
serialize-and-deserialize-bst | [Python] Json string | python-json-string-by-oystermax-hca8 | This solution may not be a perfect one due to that fact that json is not "as compact as possible". However, json is quite convineniet when it comes to web. \n\n | oystermax | NORMAL | 2021-07-26T21:08:38.824102+00:00 | 2021-07-26T21:18:29.691335+00:00 | 184 | false | This solution may not be a perfect one due to that fact that json is not "**as compact as possible**". However, json is quite convineniet when it comes to web. \n```\nclass Codec:\n\n def serialize(self, root: TreeNode) -> str:\n """Encodes a tree to a single string.\n """\n\t\t# Converts a TreeNode instance into a dict using instance.__dict__\n\t\t# Convert the dict into json string using json.dumps()\n return json.dumps(root, default=lambda x: x.__dict__)\n\n def deserialize(self, data: str) -> TreeNode:\n """Decodes your encoded data to tree.\n """\n\t\t# Convert json string into dict\n data = json.loads(data)\n\t\t\n\t\t# Recursively convert dict into TreeNode\n def _deserialize(data_dict):\n if data_dict is None:\n return None\n return TreeNode(\n val = data_dict[\'val\'],\n left = _deserialize(data_dict[\'left\']),\n right = _deserialize(data_dict[\'right\'])\n )\n return _deserialize(data)\n``` | 2 | 2 | ['Python'] | 0 |
serialize-and-deserialize-bst | C++ | Simple and Intuitive | 99% | Easy to Understand | c-simple-and-intuitive-99-easy-to-unders-ufeq | \nclass Codec {\npublic:\n void encode(TreeNode* root, string &str){\n if(root == NULL)\n return;\n str += to_string(root->val);\n | Debug_Entity | NORMAL | 2021-07-19T18:17:43.557862+00:00 | 2021-07-19T18:17:43.557902+00:00 | 341 | false | ```\nclass Codec {\npublic:\n void encode(TreeNode* root, string &str){\n if(root == NULL)\n return;\n str += to_string(root->val);\n str += "-";\n encode(root->left, str);\n encode(root->right, str);\n }\n\n // Encodes a tree to a single string.\n string serialize(TreeNode* root) {\n string str = "";\n encode(root, str);\n return str;\n }\n\n // Decodes your encoded data to tree.\n TreeNode* deserialize(string data) {\n TreeNode* root = NULL;\n stringstream ss(data);\n string value;\n while(getline(ss, value, \'-\')){\n root = insert(root, stoi(value));\n }\n return root;\n }\n \n TreeNode* insert(TreeNode* root, int data){\n if(root == NULL){\n root = new TreeNode(data);\n return root;\n }\n if(root->val > data){\n root->left = insert(root->left, data);\n return root;\n }\n else{\n root->right = insert(root->right, data);\n return root;\n }\n }\n};\n\n``` | 2 | 0 | ['Binary Search Tree', 'C', 'C++'] | 1 |
serialize-and-deserialize-bst | short ^^ | short-by-andrii_khlevniuk-geuv | Serialize: BFS, time O(N);\nDeserialize: iterative insert into BST, time O(NlogN).\n\nclass Codec \n{\npublic:\n string serialize(TreeNode* r) \n {\n | andrii_khlevniuk | NORMAL | 2021-04-09T13:36:44.937647+00:00 | 2021-04-09T14:02:48.925877+00:00 | 251 | false | **Serialize:** BFS, time `O(N)`;\n**Deserialize:** iterative insert into BST, time `O(NlogN)`.\n```\nclass Codec \n{\npublic:\n string serialize(TreeNode* r) \n {\n string out;\n for(queue<TreeNode*> q({r}); !empty(q); q.pop())\n if(q.front())\n {\n q.push(q.front()->left);\n q.push(q.front()->right);\n out += to_string(q.front()->val) + " "s;\n }\n return out;\n }\n \n TreeNode* deserialize(string d) \n {\n TreeNode* out{nullptr};\n auto r{&out};\n int val{-1};\n for(stringstream ss{d}; ss>>d; *r = new TreeNode(val))\n for(val = stoi(d), r = &out; *r; r = val<=(*r)->val ? &(*r)->left : &(*r)->right);\n return out;\n }\n};\n```\n<details>\n<summary>\nRecursive insert variation:\n</summary>\n\n```\nclass Codec \n{\npublic:\n string serialize(TreeNode* r) \n {\n string out;\n for(queue<TreeNode*> q({r}); !empty(q); q.pop())\n if(q.front())\n {\n q.push(q.front()->left);\n q.push(q.front()->right);\n out += to_string(q.front()->val) + " "s;\n }\n return out;\n }\n\n TreeNode* insert(TreeNode* r, int val)\n {\n if(!r) return new TreeNode(val);\n TreeNode* & child = val<=r->val ? r->left : r->right;\n child = insert(child, val);\n return r;\n }\n \n TreeNode* deserialize(string d) \n {\n TreeNode* out{nullptr};\n for(stringstream ss{d}; ss>>d; out = insert(out, stoi(d)));\n return out;\n }\n};\n```\n</details> | 2 | 1 | ['C', 'C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.