diff --git a/104_maximum_depth_of_binary_tree/main.cpp b/104_maximum_depth_of_binary_tree/main.cpp new file mode 100644 index 0000000..2320bce --- /dev/null +++ b/104_maximum_depth_of_binary_tree/main.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { + public: + int maxDepth(TreeNode *root) { + unordered_map visited; + int maxDepth = 0; + + function dfs = [&](TreeNode *root, int currentDepth) { + if (!root) return; + + if (visited[root]) return; + visited[root] = true; + + maxDepth = max(maxDepth, currentDepth); + + dfs(root->left, currentDepth + 1); + dfs(root->right, currentDepth + 1); + }; + + dfs(root, 1); + + return maxDepth; + } +}; \ No newline at end of file