文章目录

  • ​​1.题目​​
  • ​​2.代码​​

1.题目

  • ​​题目要求​​
  • eg:
Example:

Given binary tree [3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7
return its depth = 3.
  • 思路:求二叉树的最大深度问题用到深度优先搜索 Depth First Search,递归的完美应用,跟求二叉树的最小深度问题原理相同

2.代码

递归法
class Solution{
public:
int maxDepth(TreeNode* root)
{
if (!root) return 0;
return 1+max(maxDepth(root->left), maxDepth(root->right));
}
};


迭代法:层序遍历
class Solution
{
public:
int maxDepth(TreeNode* root)
{
int res;
queue<TreeNode*> que;
que.push(root);
while (!qye.empty())
{
+res;
for (int i=qu.size();i>0;--i)
{
TreeNode* node=que.front();que.pop();
if (!node->left) que.push(node->left);
if (!node->right) que.push(node->right);
}
}

return res;
}
};