DAY 9
0
AI & Data

## 找LeetCode上簡單的題目來撐過30天啦(DAY9)

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

## Constraints: The number of nodes in the tree is in the range [0, 104]. -100 <= Node.val <= 100

Time Limit Exceeded的程式碼

int check(struct TreeNode* root2,int D2){
if(root2 == NULL){
return 0;
}else if(root2->left != NULL || root2 -> right != NULL){
D2= D2+1;
if(check(root2->left,D2) > check(root2->right,D2)){
D2 = check(root2->left,D2);
}else{
D2 = check(root2->right,D2);
}
}
return D2;
}

int maxDepth(struct TreeNode* root){
int D = 1;
return check(root,D);
}

int check(struct TreeNode* root2,int D2){
//printf("%d\n",root2->val);
if(root2 == NULL){
return 0;
}else if(root2->left != NULL || root2 -> right != NULL){
D2= D2+1;
int l = check(root2->left,D2);
int r  =  check(root2->right,D2);
if(l > r){
D2 =l;
}else{
D2 =r;
}
}
return D2;
}

int maxDepth(struct TreeNode* root){
int D = 1;
return check(root,D);
}

DAY9心得