Talking about Binary Tree,
I will often think of Recursion.
To traverse the binary tree,
I always use Recursive Method.
So here, to find the maximum depth of binary tree,
I wrote another function to help me do this.
Because in this problem,
only using the function it gives is not convenient to use Recursive Method.
And I declared a variable "max" outside the function to storage the maximum depth,
so that I could use it in two functions.
The Runtime of the program is 3 ms.
The length of the code is 482 Bytes.
int max;
int maxD(struct TreeNode* p, int num) {
num++;
if (p->left) maxD(p->left, num);
if (p->right) maxD(p->right, num);
if (!(p->left) && !(p->right))
if (num>max)
max=num;
return max;
}
int maxDepth(struct TreeNode* root) {
max=0;
if (!root) return 0;
return maxD(root, 0);
}