二叉树]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)
发布评论