Skip to content

Add c++ code to find Maximum depth of a tree #1018

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions Tree/Maximum Tree Depth/cpp/maximum_tree_depth.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Author: Saloni Rajeev Kumar
// Date created: October 18, 2019

#include <bits/stdc++.h>
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<TreeNode*> 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;
}