题意
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
解法1—深度优先搜索,递归
没看题解自己写的,嘿嘿。
/**
* 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:
//dfs功能:求以 root 为根节点的二叉树的最大深度
int dfs(TreeNode* root)
{
if(NULL==root)
return 0;
return 1+max(dfs(root->left),dfs(root->right));
}
int maxDepth(TreeNode* root)
{
if(NULL==root)
return 0;
//我们知道了root的左右子树的最大深度后,那么整颗数的最大深度为 左右子树的最大深度+1
// +1 是为了加上本节点(root),root也算一个深度
return 1+max(dfs(root->left),dfs(root->right));
}
};
法2—层序遍历BFS(非递归)
- 树的层序遍历 / 广度优先搜索往往利用 队列 实现。
- 关键点: 每遍历一层,则计数器 +1 ,直到遍历完成,则可得到树的深度。
/**
* 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 dfs(TreeNode* root)
{
if(NULL==root)
return 0;
return 1+max(dfs(root->left),dfs(root->right));
}
int maxDepth(TreeNode* root)
{
if(NULL==root)
return 0;
// return 1+max(dfs(root->left),dfs(root->right));
// BFS实现
queue<TreeNode*> que;
int res=0;
que.push(root);
while(!que.empty())
{
res++;
int n = que.size(); //当前层的节点数
for(int i=0;i<n;++i)
{
TreeNode* node = que.front();
que.pop();
if(node->left)
que.push(node->left);
if(node->right)
que.push(node->right);
}
}
return res;
}
};