LeetCode04. Maximum Depth of Binary Tree

题意

  • 求一棵二叉树的深度

方法

  • DFS, 更新当前最大深度

代码

void dfs(TreeNode* root, int &height, int &ans)
{
    if (root == nullptr) return;
    height++;
    dfs(root->left, height, ans);
    dfs(root->right, height, ans);
    height--;
    ans = max(height, ans);
}

int maxDepth(TreeNode* root) {
    if (root == nullptr) return 0;
    int height = 1, ans = 1;
    dfs(root, height, ans);

    return ans;
}
posted @ 2022-08-29 20:01  Figure_at_a_Window  阅读(22)  评论(0)    收藏  举报