From ebd2901fe20da9fddb1ec95b80f6864ec6db0538 Mon Sep 17 00:00:00 2001 From: salonirk11 Date: Fri, 18 Oct 2019 21:06:29 +0530 Subject: [PATCH] add vertical tree traversal in cpp --- .../Vertical/cpp/vertical_traversal.cpp | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 Tree/Traverals/Vertical/cpp/vertical_traversal.cpp diff --git a/Tree/Traverals/Vertical/cpp/vertical_traversal.cpp b/Tree/Traverals/Vertical/cpp/vertical_traversal.cpp new file mode 100644 index 000000000..7f16190f7 --- /dev/null +++ b/Tree/Traverals/Vertical/cpp/vertical_traversal.cpp @@ -0,0 +1,120 @@ +// Author: Saloni Rajeev Kumar +// Date created: October 18, 2019 + +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} + }; + + class Solution { + public: + vector verticalTraversal(TreeNode* root) { + vector res; + if (!root) + return res; + + map < int,vector > m; + int hd = 0; + queue > que; + que.push(make_pair(root, hd)); + + while (!que.empty()) + { + pair temp = que.front(); + que.pop(); + hd = temp.second; + TreeNode* node = temp.first; + + m[hd].push_back(node->val); + + if (node->left != NULL) + que.push(make_pair(node->left, hd-1)); + if (node->right != NULL) + que.push(make_pair(node->right, hd+1)); + } + + map< int,vector > :: iterator it; + for (it=m.begin(); it!=m.end(); it++) + for (int i=0; isecond.size(); ++i) + res.push_back(it->second[i]); + + return res; + } + }; + +void trimLeftTrailingSpaces(string &input) { + input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) { + return !isspace(ch); + })); +} + +void trimRightTrailingSpaces(string &input) { + input.erase(find_if(input.rbegin(), input.rend(), [](int ch) { + return !isspace(ch); + }).base(), input.end()); +} + +TreeNode* stringToTreeNode(string input) { + trimLeftTrailingSpaces(input); + trimRightTrailingSpaces(input); + input = input.substr(1, input.length() - 2); + if (!input.size()) { + return nullptr; + } + + string item; + stringstream ss; + ss.str(input); + + getline(ss, item, ','); + TreeNode* root = new TreeNode(stoi(item)); + queue nodeQueue; + nodeQueue.push(root); + + while (true) { + TreeNode* node = nodeQueue.front(); + nodeQueue.pop(); + + if (!getline(ss, item, ',')) { + break; + } + + trimLeftTrailingSpaces(item); + if (item != "null") { + int leftNumber = stoi(item); + node->left = new TreeNode(leftNumber); + nodeQueue.push(node->left); + } + + if (!getline(ss, item, ',')) { + break; + } + + trimLeftTrailingSpaces(item); + if (item != "null") { + int rightNumber = stoi(item); + node->right = new TreeNode(rightNumber); + nodeQueue.push(node->right); + } + } + return root; +} + +int main() { + string line; + while (getline(cin, line)) { + TreeNode* root = stringToTreeNode(line); + + vector ret = Solution().verticalTraversal(root); + + for(auto val: ret) + cout << val << "->"; + cout<