leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

commit 22d51b2ac9fcf656701944ad4b5830acd426d3a0
parent e5aee0c096bd419cebf236201ea3f2276953c35a
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date:   Fri,  8 Dec 2023 16:16:48 +0000

Improved Daily Problem

Diffstat:
MProblems/0606.cpp | 36+++++++++++++++++-------------------
MREADME.md | 2+-
2 files changed, 18 insertions(+), 20 deletions(-)

diff --git a/Problems/0606.cpp b/Problems/0606.cpp @@ -1,26 +1,24 @@ class Solution { public: - string tree2str(TreeNode *root) { - if (!root) return ""; - + string tree2str(const TreeNode *root) { + stack<const TreeNode *> stack; + stack.push(root); string res = ""; - stack<TreeNode *> st; - unordered_set<TreeNode *> us; - st.push(root); - while (!st.empty()) { - TreeNode *root = st.top(); - if (us.find(root) != us.end()) { - res += ")"; - st.pop(); - } else { - us.insert(root); - res += "(" + to_string(root->val); - if (!root->left && !root->right) continue; - if (root->right) st.push(root->right); - if (root->left) - st.push(root->left); - else + while (!stack.empty()) { + const TreeNode *temp = stack.top(); + stack.pop(); + if (temp == nullptr) + res += ')'; + else { + res += '(' + to_string(temp->val); + stack.push(nullptr); + + if (temp->right) stack.push(temp->right); + + if (temp->left) + stack.push(temp->left); + else if (temp->right) res += "()"; } } diff --git a/README.md b/README.md @@ -361,7 +361,7 @@ for solving problems. | 0595 | Easy | [Big Countries](Problems/0595.cpp) | | 0596 | Easy | [Classes More Than 5 Students](Problems/0596.cpp) | | 0605 | Easy | [Can Place Flowers](Problems/0605.cpp) | -| 0606 | Easy | [Construct String from Binary Tree ](Problems/0606.cpp) | +| 0606 | Easy | [Construct String from Binary Tree](Problems/0606.cpp) | | 0609 | Medium | [Find Duplicate File in System](Problems/0609.cpp) | | 0610 | Easy | [Triangle Judgement](Problems/0610.cpp) | | 0617 | Easy | [Merge Two Binary Trees](Problems/0617.cpp) |