close

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 fartheast leaf node.

題意

  找一棵樹的深度,深度的意思是從根結點,可以往下走最長的距離。

想法

  一開始以為會按照大小,左右存放,但好像誤會了;原先想要先蒐集完左邊的高度,再去蒐集右邊的高度,但每次左邊蒐集完就 return,只好改改想法,新的想法是,如果 root 是空,就是回傳 0;若 root 不為空,就回傳 1 + 左邊比較長或是右邊比較長,這樣就可以找到深度。

步驟

  1. 檢查 root 是否為空

    1.1 空 return 0

    1.2 非空 return 1+max(maxDepth(root->left), maxDepth(root->right))

程式碼

int maxDepth(struct TreeNode* root) {
    if(root == NULL)
        return 0;
    else{
        return 1 + max(maxDepth(root->left), maxDepth(root->right));
    }
}

arrow
arrow
    文章標籤
    LeetCode
    全站熱搜
    創作者介紹
    創作者 Davis 的頭像
    Davis

    Epoch

    Davis 發表在 痞客邦 留言(0) 人氣()