/*
 * 演算法 / Algorithm:
 *   遞迴 DFS。空節點深度為 0；否則深度 = 1 + 較深子樹的深度。
 *   Recursive DFS. An empty node has depth 0; otherwise depth = 1 + the deeper subtree.
 *   每個節點只拜訪一次。Each node is visited exactly once.
 */

// LeetCode 已為我們定義好這個節點結構 / LeetCode predefines this node struct:
// struct TreeNode {
//     int val;                  // 節點的值 / the node's value
//     struct TreeNode *left;    // 指向左子節點的指標 / pointer to left child
//     struct TreeNode *right;   // 指向右子節點的指標 / pointer to right child
// };

// 小工具：回傳兩數中的較大者 / Helper: return the larger of two ints.
static int maxOf(int a, int b) {
    return a > b ? a : b;         // 三元運算子：a>b 成立回傳 a，否則回傳 b / ternary: pick a if a>b else b
}

int maxDepth(struct TreeNode* root) {
    // 終止條件 / Base case:
    // 若指標為 NULL（空樹或走到葉節點下方），深度就是 0。
    // If the pointer is NULL (empty tree, or past a leaf), the depth is 0.
    if (root == NULL) {
        return 0;
    }

    // 遞迴求左子樹的深度 / Recurse into the left subtree.
    // root->left 是「解參考取出 root 指向的結構，再拿它的 left 欄位」
    // root->left means "follow the root pointer, then read its left field".
    int leftDepth = maxDepth(root->left);

    // 遞迴求右子樹的深度 / Recurse into the right subtree.
    int rightDepth = maxDepth(root->right);

    // 較深的那一邊 +1（把當前節點自己算進去）就是此節點的深度。
    // The deeper side plus 1 (counting this node itself) is this node's depth.
    return 1 + maxOf(leftDepth, rightDepth);
}
