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

浙公网安备 33010602011771号