本章从两方面总结:二叉树的最大深度和N叉树的最大深度
一.二叉树的最大深度
题目描述
解法一:递归
class Solution {
public:
int maxDepth(TreeNode* root) {
if( root == NULL)
return 0;
int left_depth = maxDepth(root -> left) + 1;
int right_depth = maxDepth(root -> right) + 1;
if(left_depth >= right_depth)
return left_depth;
else
return right_depth;
}
};
这种方法容易造成堆栈的溢出。
解法二:DFS(利用堆栈)
#include<stack>
class Solution {
public:
int maxDepth(TreeNode* root) {
stack<pair<TreeNode*, int>> s;
if (root == NULL)
return 0;
s.push(pair<TreeNode*,int>(root, 1));
int maxDepth = 1;
int curDepth = 1;
while(s.empty() != 1)
{
root = s.top().first;
curDepth = s.top().second;
s.pop();
if(curDepth > maxDepth)
maxDepth = curDepth;
if (root -> left != NULL)
{
s.push(pair<TreeNode*,int>(root -> left, curDepth + 1));
}
if (root -> right != NULL)
{
s.push(pair<TreeNode*,int>(root -> right, curDepth + 1));
}
}
return maxDepth;
}
};
知识点普及:
pair是将2个数据组合成一个数据,当需要这样的需求时就可以使用pair。另一个应用是,当一个函数需要返回2个数据的时候,可以选择pair。 pair的实现是一种结构体,主要的两个成员变量是first, second 因为是使用struct不是class,所以可以直接使用pair的成员变量。
下面图帮助理解(摘自小浩算法)
方法三:BFS
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<pair<TreeNode*, int>> queue;
if (root == NULL)
return 0;
queue.push(pair<TreeNode*,int>(root, 1));
int curDepth = 0;
int mount;
while(queue.size() != 0)
{
curDepth++;
mount = queue.size();
for(int i = 0; i < mount; i++)
{
root = queue.front().first;
queue.pop();
if(root -> left != NULL)
queue.push(pair<TreeNode*,int>(root -> left, curDepth));
if(root -> right != NULL)
queue.push(pair<TreeNode*,int>(root -> right, curDepth));
}
}
return curDepth;
}
};