// 力扣104 二叉树最大深度
// 递归方法
//使用左右根后序遍历处理节点,递归方法
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root)
{
return 0;
}
int left = maxDepth(root->left);//判断左子树的深度,将左子树提取出来,进行运算
int right = maxDepth(root->right);//判断右子树的深度,将右子树提取出来,进行运算
return left>right?left+1:right+1;//判断根的深度,将左右子树提取出来进行判断谁大,并进行根的运算。
}
};
//使用根左右的前序遍历的方法实现,差不多就是深度优先遍历,有回溯法的思想
class Solution {
public:
int maxDepth(TreeNode* root) {
result = 0;
if(root==nullptr)return result;
getdepth(root,1);
return result;
}
void getdepth(TreeNode*root,int depth)
{
result=result>depth?result:depth;//判断当前根节点的深度与全部的根节点的深度比较谁大
if(!root->left&&!root->right)return;
if(root->left)
{
depth++;
getdepth(root->left,depth);
depth--;//回溯,回到之前的状态
}
if(root->right)
{
depth++;
getdepth(root->right,depth);
depth--;
}
return ;
}
private:
int result;
};
//使用层次遍历队列方法,通过使用层次遍历的方法遍历所有节点并选取当前节点进行运算
class Solution {
public:
int maxDepth(TreeNode* root) {
int x = 0;
queue<TreeNode*>qu;
if(root!=nullptr)
{
qu.push(root);
}
while(!qu.empty())
{
int size = qu.size();
for(int i=0;i<size;i++)
{
TreeNode* Node = qu.front();
qu.pop();
if(Node->left)qu.push(Node->left);
if(Node->right)qu.push(Node->right);
if(i == (size-1))
{
x++;
}
}
}
return x;
}
};
// 二叉树的最小深度
// 递归方法
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root)
{
return 0;
}
if(!root->left&&!root->right)//全是空节点
{
return 1;
}
else if(!root->left&&root->right||!root->right&&root->left)//空节点为左右节点中的两个当中的一个
{
root = root->left?root->left:root->right;
return minDepth(root)+1;
}
else
{
int left = minDepth(root->left)+1;
int right = minDepth(root->right)+1;
return left>right?right:left;
}
}
};
// 队列方法
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*>qu;
int count = 0;
if(root!=nullptr)
{
qu.push(root);
count = 1;
}
while(!qu.empty())
{
int size = qu.size();
for(int i=0;i<size;i++)
{
TreeNode* Node = qu.front();
qu.pop();
if(Node->left)qu.push(Node->left);
if(Node->right)qu.push(Node->right);
if( !Node->left && !Node->right)//判断两个节点为空的时候,直接返回count
{
return count;
}
}
count++;
}
return count;
}
};