题目:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
思路一:广度优先遍历
分析:求出树的最大深度,也就是计算树有多少层,访问每层元素,然后将层数+1,直到最后一层,即可的最大深度。
int maxDepth(TreeNode* root) {
int res=0;
if(root==NULL)
return res;
queue<TreeNode*>que;
que.push(root);
while(!que.empty())
{
int len=que.size();
for(int i=0;i<len;i++)
{
TreeNode*node=que.front();
que.pop();
if(node->left)
que.push(node->left);
if(node->right)
que.push(node->right);
}
res++;
}
return res;
}
思路二; 深度优先遍历(后序遍历)
分析:后序遍历
步骤:
-
确定递归函数的参数和返回值
确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int类型。
-
确定递归终止的条件
如果为空节点的话,就返回0,表示高度为0
-
确定单层逻辑
先求左子树的深度,再求右子树的深度,最后取左右子树深度最大的+1就是当前结点的树的深度作为返回值
class Solution {
public:
int getDepth(TreeNode* node) {
if (node == NULL) return 0;
int leftDepth = getDepth(node->left); // 左
int rightDepth = getDepth(node->right); // 右
int depth = 1 + max(leftDepth, rightDepth); // 中
return depth;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
};
精简后的代码
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};