一、二叉树树的遍历
1)递归方法
void PreOrder(BiNode *root)
{
if(root==NULL)
return;
else
{
cout<<root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
2)非递归伪代码
template <class T>
void BiTree::PreOrder(BiNode<T> *root) {
SeqStack<BiNode<T> *> s;
while (root!=NULL | | !s.empty()) {
while (root!= NULL) {
cout<<root->data;
s.push(root);
root=root->lchild;
}
if (!s.empty()) {
root=s.pop();
root=root->rchild;
}
}
}
步骤解析:
1.栈s初始化;
2.循环直到root为空且栈s为空
2.1 当root不空时循环
2.1.1 输出root->data;
2.1.2 将指针root的值保存到栈中;
2.1.3 继续遍历root的左子树
2.2 如果栈s不空,则
2.2.1 将栈顶元素弹出至root;
2.2.2 准备遍历root的右子树;
二、求二叉树的结点个数
1)
void Count(BiNode *root){
if (root) {
Count(root->lchild);
number+ +; //number为数据成员
Count(root->rchild);
}
}
template<class T>
int BiTree<T>::count(BiNode<T>* root){
int number=0;
if (root==NULL)
number=0;
else
number=count(root->lchild)+count(root->rchild)+1;
return number;
}
三、求二叉树中叶子结点个数
1)
template<typename T>
void BiTree<T>:: countleaf(BiTreeNode<T> * root){
if (root) {
if (root->lchild==NULL && root->rchild==NULL)
leafcount=leafcount+1;
else
{
countleaf(root->lchild);
countleaf(root->rchild);
}
}
return;
}
template<class T>
int BiTree<T>::leafcount(BiNode<T>* root){
int number=0;
if (root==NULL)
number=0;
else if(root->lchild==NULL && root->rchild==NULL)
number=1;
else
number=leafcount(root->lchild)+leafcount(root->rchild);
return number;
}
四、计算二叉树的高度
int getheight(BiNode *root)
{
int lheight=0,rheight=0;
if(root==0)
return 0;
lheight=getheight(root->lchild);
rheight=getheight(root->rchild);
if(lheight>rheight)
return lheight+1;
else
return rheight+1;
}
五、二叉树左右子树的交换
void exchange(BiNode* root)
{
if(root)
{
BiNode* temp;
temp=root->lchild;
root->lchild=root->rchild;
root->rchild=temp;
exchange(root->lchild);
exchange(root->rchild);
}
else
return ;
}