From eec69d18f5e284eb4988ae15e053f00a918da900 Mon Sep 17 00:00:00 2001 From: salonirk11 Date: Fri, 18 Oct 2019 20:04:25 +0530 Subject: [PATCH] add cpp code for maxium tree depth --- .../cpp/maximum_tree_depth.cpp | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Tree/Maximum Tree Depth/cpp/maximum_tree_depth.cpp diff --git a/Tree/Maximum Tree Depth/cpp/maximum_tree_depth.cpp b/Tree/Maximum Tree Depth/cpp/maximum_tree_depth.cpp new file mode 100644 index 000000000..8f1efc5fe --- /dev/null +++ b/Tree/Maximum Tree Depth/cpp/maximum_tree_depth.cpp @@ -0,0 +1,91 @@ +// 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: + int maxDepth(TreeNode* root) { + // Recursive DFS solution + return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1; + } +}; + +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); + + int ret = Solution().maxDepth(root); + + string out = to_string(ret); + cout << out << endl; + } + return 0; +}