题目
104. 二叉树的最大深度
我的思路
深搜递归,广搜队列
我的实现
/** * 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) { //广搜三件套:初始化队列,加一个队头,遍历队列 //队列元素:节点+当前层数 int maxDepth=0; queue<pair<TreeNode*,int>> q; if(root!=NULL) q.push(make_pair(root,1)); while(!q.empty()){ pair temp = q.front(); q.pop(); maxDepth = max(maxDepth,temp.second); if(temp.first->left!=NULL) q.push(make_pair(temp.first->left,temp.second+1)); if(temp.first->right!=NULL) q.push(make_pair(temp.first->right,temp.second+1)); } return maxDepth; } }; //深搜or广搜 /*深搜 class Solution { public: int search(TreeNode *root){ if(root==NULL)return 0; int length = 1; if (root->left!=NULL){ length = search(root->left)+1; } if(root->right!=NULL){ length = max(length,search(root->right)+1); } return length; } int maxDepth(TreeNode* root) { return search(root); } }; */ /*广搜 class Solution { public: int maxDepth(TreeNode* root) { //广搜三件套:初始化队列,加一个队头,遍历队列 //队列元素:节点+当前层数 int maxDepth=0; queue<pair<TreeNode*,int>> q; if(root!=NULL) q.push(make_pair(root,1)); while(!q.empty()){ pair temp = q.front(); q.pop(); maxDepth = max(maxDepth,temp.second); if(temp.first->left!=NULL) q.push(make_pair(temp.first->left,temp.second+1)); if(temp.first->right!=NULL) q.push(make_pair(temp.first->right,temp.second+1)); } return maxDepth; } }; */
深搜广搜时间复杂度都是n,n为节点数。空间复杂度都是logn,层数。
拓展学习
更简洁的深搜写法
class Solution { public: int maxDepth(TreeNode* root) { if (root == nullptr) return 0; return max(maxDepth(root->left), maxDepth(root->right)) + 1; } }; 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/er-cha-shu-de-zui-da-shen-du-by-leetcode-solution/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。