iT邦幫忙

2021 iThome 鐵人賽

DAY 9
0
AI & Data

想到甚麼打甚麼系列 第 9

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

題號:104 標題:Maximum Depth of Binary Tree難度:Easy

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.

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:
Input: root = [1,null,2]
Output: 2

Example 3:
Input: root = []
Output: 0

Example 4:
Input: root = [0]
Output: 1

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);
}

花比較多的時間
今天花比較多時間在解決Time Limit Exceeded的問題,最後發現我在if裡面recursive,導致不必要的call function,改為用變數存return的值再去做判斷,就沒有這個問題啦

DAY9心得
我想離職了,有沒有公司缺人啊


上一篇
找LeetCode上簡單的題目來撐過30天啦(DAY8)
下一篇
找LeetCode上簡單的題目來撐過30天啦(DAY10)
系列文
想到甚麼打甚麼30

尚未有邦友留言

立即登入留言