[二叉树]leetcode104:二叉树的最大深度(easy)

编程入门 行业动态 更新时间:2024-10-27 00:32:09

[<a href=https://www.elefans.com/category/jswz/34/1769924.html style=二叉树]leetcode104:二叉树的最大深度(easy)"/>

[二叉树]leetcode104:二叉树的最大深度(easy)

题目:

题解1:递归法解题

class Solution {
public:int maxDepth(TreeNode* root) {if(root==nullptr) return 0;else return 1+max(maxDepth(root->left),maxDepth(root->right));}
};

题解2:利用层序遍历迭代法解题

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     TreeNode *left;*     TreeNode *right;*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:int maxDepth(TreeNode* root) {/*解法2:利用层序遍历进行计算二叉树的深度*/if(root==nullptr)return 0;int count=0;queue<TreeNode*> qt;qt.push(root);while(!qt.empty()){++count;//每层的size大小已经确定,依次将当前层的节点的左右子树进队列即可for(int i=qt.size();i>0;--i)//使用qt.size()初始化i的好处是避免了size的失效,同样也可以提前声明{TreeNode *node=qt.front();qt.pop();// if(node->left)qt.push(node->left);//当前节点的左子树进队列if(node->left)qt.push(node->left);if(node->right)qt.push(node->right);//当前节点的右子树进队列}}return count;}
};

更多推荐

[二叉树]leetcode104:二叉树的最大深度(easy)

本文发布于:2023-07-28 18:50:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279329.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:二叉树   深度   easy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!