From 4f2d4f58de69e6c203a4419e1f140afff57d5a0b Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Wed, 5 Mar 2025 23:54:24 +0800 Subject: [PATCH] feat: 104_maximum_depth_of_binary_tree --- 104_maximum_depth_of_binary_tree/main.cpp | 35 +++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 104_maximum_depth_of_binary_tree/main.cpp 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