diff --git a/CS notes/pages/Leetcode Maximum-Depth-Of-Binary-Tree.md b/CS notes/pages/Leetcode Maximum-Depth-Of-Binary-Tree.md index b6b0c3b..9b56d80 100644 --- a/CS notes/pages/Leetcode Maximum-Depth-Of-Binary-Tree.md +++ b/CS notes/pages/Leetcode Maximum-Depth-Of-Binary-Tree.md @@ -56,12 +56,38 @@ BFS way: Simply log the level in each while iteration. DFS way: (Popular) -Use recursion +Use recursion: +- Base Case: + - root == nullptr: return 0; +- maxDepth(root) = max(maxDepth(root->left), maxDepth(root->right)) ### Solution DFS Recursion: ```cpp +/** + * Definition for a binary tree node. + * 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) { + // DFS + if (!root) { + return 0; + } + + return max(maxDepth(root->left), maxDepth(root->right)) + 1; + } +}; ``` BFS: