【随便写写】数据结构——二叉树的基本操作

一、二叉树树的遍历

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 ;
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值