From 547ec59bbc04856f70a2cabf5304ed281fcbdf27 Mon Sep 17 00:00:00 2001 From: NALIN AGRAWAL <54065357+nalin-programmer@users.noreply.github.com> Date: Tue, 3 Oct 2023 17:33:39 +0530 Subject: [PATCH] Create Construct_Binary_Tree_From_Bracket_Parenthesis.cpp --- ...t_Binary_Tree_From_Bracket_Parenthesis.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 C++/Construct_Binary_Tree_From_Bracket_Parenthesis.cpp diff --git a/C++/Construct_Binary_Tree_From_Bracket_Parenthesis.cpp b/C++/Construct_Binary_Tree_From_Bracket_Parenthesis.cpp new file mode 100644 index 0000000..912e7fc --- /dev/null +++ b/C++/Construct_Binary_Tree_From_Bracket_Parenthesis.cpp @@ -0,0 +1,46 @@ +#include +using namespace std; + +class Solution{ +public: + Node *treeFromString(string str){ + string cur = ""; + int i = 0, num, n = str.length(); + while (i < n && str[i] != '(' && str[i] != ')') { + cur += str[i++]; + } + num = stoi(cur); + Node *root = new Node(num); + stack st; + st.push(root); + for (; i < n; i++) { + if (str[i] == '(') { + cur = ""; + while (str[i + 1] != '(' && str[i + 1] != ')') { + i++; + cur += str[i]; + } + num = stoi(cur); + Node *temp = new Node(num); + if (!st.top()->left) + st.top()->left = temp; + else + st.top()->right = temp; + st.push(temp); + } + else if (str[i] == ')') + st.pop(); + } + return root; + } +}; + +int main(){ + int t;cin>>t; + while(t--){ + string s;cin>>s; + Solution obj; + Node *root = obj.treeFromString(s); + } + return 0; +}