Advertisement
LikeRampage

C++ leetcode 331. Verify Preorder Serialization of a Binary Tree Chatgpt unlimited

Apr 22nd, 2024 (edited)
698
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.64 KB | None | 0 0
  1. #include <string>
  2. #include <sstream>
  3. #include <stack>
  4.  
  5. class Solution {
  6. public:
  7.     bool isValidSerialization(std::string preorder) {
  8.         std::istringstream iss(preorder);
  9.         std::string node;
  10.         std::stack<std::string> stack;
  11.  
  12.         while (std::getline(iss, node, ',')) {
  13.             while (node == "#" && !stack.empty() && stack.top() == "#") {
  14.                 stack.pop();
  15.                 if (stack.empty()) {
  16.                     return false;
  17.                 }
  18.                 stack.pop();
  19.             }
  20.             stack.push(node);
  21.         }
  22.  
  23.         return stack.size() == 1 && stack.top() == "#";
  24.     }
  25. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement