力扣104. 二叉树的最大深度(递归DFS、迭代BFS&DFS)
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
方法一:递归recursive
递归,DFS(深度优先搜索)
复杂度分析:
时间复杂度:我们每个结点只访问一次,因此时间复杂度为 O(N),其中 N 是结点的数量。
空间复杂度:在最糟糕的情况下,树是完全不平衡的,例如每个结点只剩下左子结点,递归将会被调用 N 次(树的高度),因此保持调用栈的存储将是 O(N)。但在最好的情况下(树是完全平衡的),树的高度将是 log(N)。因此,在这种情况下的空间复杂度将是 O(log(N))。
//递归,DFS(深度优先搜索)
int maxDepthrecursive(TreeNode* root)
{
//递归终止条件
if (root == nullptr)return 0;
//左子树或者右子树最大深度,加上根节点的一层
return max(maxDepthrecursive(root->left), maxDepthrecursive(root->right)) + 1;
}
方法二:迭代iteration(队列,BFS)
层序遍历,队列,BFS(广度优先搜索)
复杂度分析
- 时间复杂度:O(N)。
- 空间复杂度:O(N)。
//层序遍历,队列,BFS(广度优先搜索)
int maxDepthiteration(TreeNode* root)
{
//鲁棒性,如果为空树,直接返回0层
if (root == nullptr)return 0;
//当前层的个数curcount,记录有几个结点,初始化为零
int curcount = 0;
//当前树的深度depth,记录有几层,初始化为零
int depth = 0;
//下一层的个数nextcount,下一层有几个结点,初始化为1(代表根节点)
int nextcount = 1;
queue<TreeNode*>que;
que.push(root);
while (!que.empty())
{
TreeNode* temp = que.front();
que.pop();
//非空结点,层序遍历
cout << temp->val << '\t' << depth << '\n';
curcount++;
//叶结点,跳过
if (temp->left)que.push(temp->left);
if (temp->right)que.push(temp->right);
//当前层遍历的结点等于nextcount时,说明要换一层了
//depth加一,curcount初始化为零,nextcount为当前队列的个数
if (curcount == nextcount)
{
depth++;
curcount = 0;
nextcount = que.size();
}
}
return depth;
}
方法三:迭代iteration(栈,DFS)
挖个坑
四、汇总
#include "stdafx.h"
#include<queue>
#include<vector>
#include <iostream>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
//递归,DFS(深度优先搜索)
int maxDepthrecursive(TreeNode* root)
{
//递归终止条件
if (root == nullptr)return 0;
//左子树或者右子树最大深度,加上根节点的一层
return max(maxDepthrecursive(root->left), maxDepthrecursive(root->right)) + 1;
}
//层序遍历,队列,BFS(广度优先搜索)
int maxDepthiteration(TreeNode* root)
{
//鲁棒性,如果为空树,直接返回0层
if (root == nullptr)return 0;
//当前层的个数curcount,记录有几个结点,初始化为零
int curcount = 0;
//当前树的深度depth,记录有几层,初始化为零
int depth = 0;
//下一层的个数nextcount,下一层有几个结点,初始化为1(代表根节点)
int nextcount = 1;
queue<TreeNode*>que;
que.push(root);
while (!que.empty())
{
TreeNode* temp = que.front();
que.pop();
//非空结点,层序遍历
cout << temp->val << '\t' << depth << '\n';
curcount++;
//叶结点,跳过
if (temp->left)que.push(temp->left);
if (temp->right)que.push(temp->right);
//当前层遍历的结点等于nextcount时,说明要换一层了
//depth加一,curcount初始化为零,nextcount为当前队列的个数
if (curcount == nextcount)
{
depth++;
curcount = 0;
nextcount = que.size();
}
}
return depth;
}
};
int main()
{
TreeNode p[13] = { 2,3,3,4,5,5,4,NULL,NULL,8,9,9,8 };
p[0].left = &p[1]; p[0].right = &p[2];
p[1].left = &p[3]; p[1].right = &p[4];
p[2].left = &p[5]; p[2].right = &p[6];
//p[3].left = &p[7]; p[3].right = &p[8];
p[4].left = &p[9]; p[4].right = &p[10];
p[5].left = &p[11]; p[5].right = &p[12];
Solution s;
auto resultrecursive = s.maxDepthrecursive(p);
auto resultiteration = s.maxDepthiteration(p);
return 0;
}