【数据结构二叉树复习】

1、节点的定义:

template <class Elem>
class TreeNode
{
private:
Elem it;//数据域
TreeNode* lc;//左孩子
TreeNode* rc;//右孩子
public:
TreeNode()
{
lc = rc = NULL;
}
TreeNode(Elem e, TreeNode* l = NULL, TreeNode* r = NULL)
{
it = e; lc = l; rc = r;
}
~TreeNode(){}
bool isLeaf()
{
return (lc == NULL) && (rc == NULL);
}
};


2、二叉树:(链表法、由上往下建树)

template <Elem>
class Tree
{
private:
TreeNode<Elem>* subroot;//根节点
TreeNode<Elem>* tail;//指向最后一个节点的指针
public:
Tree()//构造函数
{
subroot = NULL;
tail = subroot;
}
~Tree(){}
void insert(const Elem& item);//建树、插入节点
void xianxu(TreeNode<Elem>* subroot);//先序遍历
void zhongxu(TreeNode<Elem>* subroot);//中序遍历
void houxu(TreeNode<Elem>* subroot);//后续遍历
};


//玩二叉树最重要的就是遍历遍历再遍历。。。

template <Elem>
void Tree::insert(const Elem& item)
{
if (suboot == NULL)//根节点为空的情况
{
subroot = new TreeNode(item, NULL, NULL);
}
else
{
TreeNode<Elem>* newnode; 
newnode = new TreeNode<Elem>(item, NULL, NULL);
if (tail->lc == NULL)
{
tail->lc = newnode;
}
else
{
tail->rc == newnode;
tail = tail->lc;
}
}
}


template <Elem>
void Tree::xianxu(TreeNode<Elem>* subroot)//先序遍历,递归方法
{
if (subroot == NULL)
return;
cout << subroot->it << " ";
xianxu(subroot->lc);
xianxu(subroot->lr);
}


template <Elem>
void Tree::zhongxu(TreeNode<Elem>* subroot)//中序遍历,递归方法
{
zhongxu(subroot->lc);
if (subroot == NULL)
return;
cout << subroot->it << " ";
zhongxu(subroot->lr);
}


template <Elem>
void Tree::houxu(TreeNode<Elem>* subroot)//后序遍历,递归方法
{
houxu(subroot->lc);
houxu(subroot->lr);
if (subroot == NULL)
return;
cout << subroot->it << " ";
}


二叉查找树、哈夫曼树、堆什么的,,我决定明天再看。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值