Given a binary tree to find its maximum depth.
The depth of the binary tree is the root node to the nodes on the longest path farthest leaf node.
Description: leaf node is a node has no child nodes.
Example:
given binary tree [3,9,20, null, null, 15,7 ],
3
/ \
9 20
/ \
15 7
Return to its maximum depth of 3.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int DFS(struct TreeNode* root)
{
if(!root)return 0;
int left_depth=0,right_depth=0;
if(root->left)left_depth=DFS(root->left);
if(root->right)right_depth=DFS(root->right);
return left_depth>right_depth?left_depth+1:right_depth+1;
}
int maxDepth(struct TreeNode* root){
return DFS(root);
}
When execution: 8 ms, beat the 96.93% of all users in C submission
Memory consumption: 9.3 MB, defeated 99.58% of all users in C submission