similar to maximum depth of a binary tree, except we are essentially finding the max depths for the right and left subtrees of the root and adding them together
π€What Did I Struggle With?
- when to use the provided function for DFS and when to create a helper function
- depends on the persistence of the result
π‘ Explanation of Solution
- dfs helper function that takes in the TreeNode and a reference to the result
- recursively explore the left and right subtrees
- calculate the res by taking the max between the current res and the sum between the left and right subtree recursive values
- return 1 + max(left,right)
β Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(log n) - O(n) due to recursion stack depending on balance of tree
π» Implementation of Solution
/** * 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 {private: int dfs(TreeNode* root, int& res) { if(root == nullptr) return 0; int leftSubtree = dfs(root->left, res); int rightSubtree = dfs(root->right, res); res = max(res, leftSubtree + rightSubtree); return 1 + max(leftSubtree, rightSubtree); }public: int diameterOfBinaryTree(TreeNode* root) { int res = 0; dfs(root, res); return res; }};