题目要求
104. 二叉树的最大深度
题解
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/cde-san-chong-fang-fa-shi-xian-you-zhu-jie-by-zzxh/
递归
当前高度=max(左子树高度,右子树高度)+1
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
深度优先:用栈的循环版
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL) return 0;
stack<pair<TreeNode*,int>> s;
TreeNode* p=root;
int Maxdeep=0;
int deep=0;
while(!s.empty()||p!=NULL)
{
while(p!=NULL)
{
s.push(pair<TreeNode*,int>(p,++deep));
p=p->left;
}
p=s.top().first;
deep=s.top().second;
if(Maxdeep<deep) Maxdeep=deep;
s.pop();
p=p->right;
}
return Maxdeep;
}
};
广度优先:使用队列
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL) return 0;
deque<TreeNode*> q;
q.push_back(root);
int deep=0;
while(!q.empty())
{
deep++;
int num=q.size();
for(int i=0;i<num;i++)
{
TreeNode* p=q.front();
q.pop_front();
if(p->left) q.push_back(p->left);
if(p->right) q.push_back(p->right);
}
}
return deep;
}
};
语法学习
pair
C++ pair的基本用法总结(整理)
deque
C++ deque的总结
[C++ STL] deque使用详解