(一)求二叉树的深度
如果一棵树只有一个结点,那么它的深度为1;
如果根结点只有左子树没有右子树,那么树的深度是左子树的深度加1,加1是加上根节点这一层
如果既有左子树又有右子树,那么树的深度应该是左、右子树中深度较大的值再加1
递归代码
int Depth1(BtNode* ptr)
{
if(ptr == NULL)
return 0;
int nleft = Depth1(ptr->leftchild);
int nright = Depth1(ptr->rightchild);
return nleft > nright ? nleft + 1:nright+1;
}
非递归 借用队列实现
1.先将root节点入队
2.在每次数据出队之前计算队内数据的数量size, 用size控制出队次数
3.每一层size之后depth加1
4.最后知道队空,返回depth的值
int Depth2(BtNode* ptr)
{
if(ptr == NULL)
return 0;
if(ptr->leftchild == NULL && ptr->rightchild == NULL)
return 1;
queue<BtNode*> qu;
qu.push(ptr);
int depth = 0;
while(!qu.empty())
{
int size = qu.size();
depth++;
for(int i = size;i > 0 ;--i)
{
ptr = qu.front();qu.pop();
if(ptr->leftchild != NULL)
qu.push(ptr->leftchild);
if(ptr->rightchild != NULL)
qu.push(ptr->rightchild);
}
}
return depth;
}
(二)层次遍历二叉树
借助队列实现层次遍历
void NiceLevelOrder(BtNode *ptr)
{
if(ptr == NULL) return ;
queue<BtNode*> qu;
qu.push(ptr);
while(!qu.empty())
{
ptr = qu.front();qu.pop();
cout<<ptr->key<< " ";
if(ptr->leftchild != NULL)
{
qu.push(ptr->leftchild);
}
if(ptr->rightchild != NULL)
{
qu.push(ptr->rightchild);
}
}
cout<<endl;
}
借助深度特性循环遍历二叉树
void LevelOrder(BtNode* ptr)
{
if(ptr == NULL )
return ;
int level = Depth1(ptr);
for(int i = 0 ; i < level;++i)
{
Print_K_Level_Item(ptr,i);
}
cout<<endl;
}
(三)打印二叉树第K层节点
递归代码
void Print_K_Level_Item(BtNode *ptr,int k)
{
if(ptr == NULL || k < 0)
return ;
if(ptr != NULL && k == 0)
cout<<ptr->key<<" ";
else
{
Print_K_Level_Item(ptr->leftchild,k-1);
Print_K_Level_Item(ptr->rightchild,k-1);
}
}
非递归代码
主要思路图
void Print_K_Node(BtNode* ptr,int k)
{
if(ptr == NULL)
return ;
if(ptr != NULL && k == 1)
cout<<ptr->key<<" ";
else
{
queue<BtNode*> qu;
qu.push(ptr);
int depth = 0;
int len = 0;
while(!qu.empty())
{
int size = qu.size();
len = size;
depth++;
if(depth == k)
{
for(int i = 0 ;i < size ;++i)
{
ptr = qu.front(); qu.pop();
cout<<ptr->key<<" ";
len--;
}
if(len == 0)
break;
}
for(int i = 0 ; i < size ;++i)
{
ptr = qu.front();qu.pop();
if(ptr->leftchild != NULL)
{
qu.push(ptr->leftchild);
}
if(ptr->rightchild != NULL)
{
qu.push(ptr->rightchild);
}
}
}
}
}