9.2三七笔试

tech2022-08-28  111

力扣.104. 二叉树的最大深度 题目:给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。

题解思路:

方法一:队列+层序遍历

函数代码:

class Solution { public: int maxDepth(TreeNode* root) { if(!root) { return 0; } queue<TreeNode *>q; q.push(root); int res=0; while(!q.empty()) { int len=q.size(); while(len) { TreeNode *cur=q.front(); q.pop(); if(cur->left) { q.push(cur->left); } if(cur->right) { q.push(cur->right); } len--; } res++; } return res; } };

方法二:递归

函数代码:

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

力扣322.零钱兑换

最新回复(0)