104. Maximum Depth of Binary Tree (Tree; DFS)
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
class Solution { public: int maxDepth(TreeNode *root) { if(!root) return 0; max_depth = 0; dfs(root,1); return max_depth; } void dfs(TreeNode * current, int depth) { if(current->left) { dfs(current->left, depth+1); } if (current->right) { dfs(current->right,depth+1); } if(!current->left && !current->right) { if(depth > max_depth){ max_depth = depth; } } } private: int max_depth; };