✔ C++ || CLEAN Code || EASY Solution with DETAILED Explanation
Solution :\n\nIn Preorder traversal we first record the current node value and then we traverse the left and right children of that node.\n\nAfter observing the
**Solution :**\n\nIn Preorder traversal we first record the current node value and then we traverse the left and right children of that node.\n\nAfter observing the preorder traversal of various binary trees we notice two things :\n\n1.  A leaf node will always be followed by two \'#\' ( which represent NULL values and also that we do not have to traverse this subtree).\n2.  We can replace an entire subtree with a \'#\' after we have finished traversing that subtree. The \'#\' indicates that this subtree has already been traversed and we need to move on to the next child.\n\n**Refer the example below to understand the concept better.**\n\n![image](https://assets.leetcode.com/users/images/0ffb9e91-7dc9-4429-9683-c18c65279216_1661179462.6552796.png)\n\nA stack data structure will be of great help to track the nodes and remove them easily.\n\n**CODE : **\n\n```\nclass Solution {\npublic:\n    bool isValidSerialization(string preorder) {\n        stringstream s(preorder);\n        stack<string> st;\n        string str;\n        \n        while(getline(s, str, \',\')){\n            if(st.empty() || str != "#") st.push(str);\n            else{\n                while(!st.empty() && st.top() == "#"){\n                    st.pop();\n                    if(st.empty()) return false;\n                    else st.pop();\n                }\n                \n                st.push(str);\n            }\n        }\n        \n        return st.size() == 1 && st.top() == "#";\n    } \n};
['Stack', 'C', 'C++']