104. 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
方法一 深度优先遍历 递归
这个方法看一眼就懂了 不讲了
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL)
return 0;
int depthleft=maxDepth(root->left);
int depthright=maxDepth(root->right);
return max(depthleft,depthright)+1;
}
};
方法二 深度优先遍历 栈循环
同样是用到DFS思想,使用栈来保存节点,而且每次进栈的时候要把当前深度保存一下,然后深度遍历到某一个叶节点,就比较最大深度和当前深度的值,来得到最大的深度。他比较麻烦,需要实时更新当前深度。创建pair同时在栈里存放结点和当前深度。
核心代码
class Solution {
public:
int maxDepth(TreeNode* root) {
int maxDEp=0;
stack<pair<TreeNode*,int>>p;
if(root)
{
p.push(pair<TreeNode*,int>(root,1));//放入根节点
}
while(!p.empty())
{
TreeNode*cur=p.top().first;//栈不为空取出栈顶元素和当前深度
int curDep=p.top().second;
p.pop();//栈顶元素出栈
maxDEp=maxDEp>curDep? maxDEp:curDep;//和最大深度比较
if(cur->left) p.push(pair<TreeNode*,int>(cur->left,curDep+1));//这里最容易想不明白了,我就是被curDep+1忽悠了,虽然这里加一了,但是它并没有赋值给curDep,这一点切记,只有当执行到 int curDep=p.top().second时,curDep也就是当前深度才会加一
if(cur->right) p.push(pair<TreeNode*,int>(cur->right,curDep+1));
}
return maxDEp;//退出循环返回最大值
}
};
测试代码
上面的核心程序不懂得,可以直接把我下面的测试代码复制到VS上Debug调试一下
#include "stdafx.h"
#include<stack>
#include<iostream>
using namespace std;
struct TreeNode
{
int val;
struct TreeNode*left;
struct TreeNode*right;
struct TreeNode(int data) :val(data), left(nullptr), right(nullptr) {
}
};
int maxDepth(TreeNode* root) {
int maxDEp = 0;
stack<pair<TreeNode*, int>>p;
if (root)
{
p.push(pair<TreeNode*, int>(root, 1));
}
while (!p.empty())
{
TreeNode*cur = p.top().first;
int curDep = p.top().second;
p.pop();
maxDEp = maxDEp>curDep ? maxDEp : curDep;
if (cur->left) p.push(pair<TreeNode*, int>(cur->left, curDep + 1));
if (cur->right) p.push(pair<TreeNode*, int>(cur->right, curDep + 1));
}
return maxDEp;
}
int main()
{
TreeNode *head = new TreeNode(3);
head->left = new TreeNode(9);
head->right = new TreeNode(20);
/*head->left->left = new TreeNode(2);
head->left->right = new Node(4);*/
//head->left->left->left = new Node(1);
head->right->left = new TreeNode(15);
//head->right->left->left = new Node(6);
head->right->right = new TreeNode(7);
/*head->right->right->left = new Node(9);
head->right->right->right = new Node(11);*/
int a=maxDepth(head);
cout << a << endl;
return 0;
}
方法三 广度优先搜索 队列
使用队列来保存节点,就一层一层遍历,每次遍历完一层的节点,深度+1就好了。遍历到最后一层的深度就是最大深度。这个简单一些 看代码容易理解
class Solution {
public:
int maxDepth(TreeNode* root) {
int depth=0;
deque<TreeNode*>p;
if(root==NULL)
return 0;
p.push_back(root);
while(!p.empty())
{
depth++;
int num=p.size();
for(int i=1;i<=num;i++)
{
TreeNode*q=p.front();
p.pop_front();
if(q->left)p.push_back(q->left);
if(q->right)p.push_back(q->right);
}
}
return depth;
}
};