[Python3/Java] Easy Solution Explained in Detail | O(1) Space
Whoever is downvoting, please comment and let me know how I can improve.\n\nBASICS\n- Preorder traversal follows the following logic:\n\t- explore the current n
Whoever is downvoting, please comment and let me know how I can improve.\n\n***BASICS***\n- **Preorder traversal** follows the following logic:\n\t- explore the current node\n\t- recurse left\n\t- recurse right\n- In our case, we define a binary tree by saying two things:\n\t- Each **null node** has `0` children.\n\t- Each **non-null node** has `2` children - can be either null nodes or non-null nodes.\n\n![image](https://assets.leetcode.com/users/images/290876ad-ba4c-4cca-892f-4d4f6ef4ab7e_1629963000.540849.png)\n\n***LOGIC***\nWe say that a tree is valid if it follows both of the above conditions. It basically looks like we need to **keep a track of the number of children**. Let\'s call it `slots` as in the slots we can fill each child in.\n\nSo, a null node gives `0` children and consumes `1` space. Giving a total of `-1`.\n\nA non-null node consumes `1` space similarly, but produces space for `2` more. So,\n\n- `-1` for null node\n- `+1` for valid node\n\nWe now only need to count the `slots`! `solts` themselves follow 2 more conditions:\n- They are always `>0` during the program run\n- They are `==0` at the end of the run.\n\nAnd that\'s it!\n\n***CODE***\nPython3\n```\nclass Solution:\n    def isValidSerialization(self, preorder: str) -> bool:\n        nodes = preorder.split(\',\')\n        slots = 1\n        for node in nodes:\n            if slots <= 0: return False\n            slots += -1 if node == \'#\' else 1\n        return slots == 0\n```\n\nJava\n```\nclass Solution {\n    public boolean isValidSerialization(String preorder) {\n        String[] nodes = preorder.split(",");\n        int slots = 1;\n        for(String node: nodes) {\n            if (slots <= 0) return false;\n            if (node.equals("#")) slots--;\n            else slots++;\n        }\n        return slots == 0;\n    }\n}\n```\n\n***COMPLEXITY ANALYSIS***\n- Time: `O(N)` where N is the total number of nodes.\n- Space: `O(1)` since we only store 1 variable.\n\n**Upvote if this helps :D Feedback/Discussions are welcome!**\n
[]