二叉树叶子结点个数计算.docxVIP

  • 4
  • 0
  • 约2.5千字
  • 约 4页
  • 2021-07-19 发布于陕西
  • 举报
二叉树叶子结点个数计算 二叉树叶子结点个数计算 计算二叉树叶子结点 1.程序设计简介 已知一棵二叉树,求该二叉树中叶子结点的个数。 (1) 设计二叉树的二叉链表为存储结构 (2) 设计求叶子结点个数的递归算法 (3) 输入:一颗二叉树 (4) 输出:二叉树中叶子结点的个数 (1)存储设计 二叉树采用二叉链表为存储结构 (2)算法设计 求二叉树中叶子结点个数,即求二叉树的所有结点中左、右子树均为空的结点个数之和。可以将此问题转化为遍历问题,在遍历中“访问一个结点”时判断该结点是不是叶子,若是则将计数器累加。 #include #include using namespace std; struct BiNode //二叉树的结点结构 char data; BiNode *lchild, *rchild; class BiTree public: BiTree( ); //构造函数,初始化一棵二叉树,其前序序列由键盘输入 ~BiTree(void); //析构函数,释放二叉链表中各结点的存储空间 BiNode* Getroot(); //获得指向根结点的指针 void PreOrder(BiNode *root); //前序遍历二叉树 void BiTree::yezi(BiNode *root,int n); private: BiNode *root; //指向根结点的头指针 BiNode *Creat( ); //有参构造函数调用 void Release(BiNode *root); //析构函数调用 BiTree::BiTree( ) BiTree::~BiTree(void) BiNode* BiTree::Getroot( ) void BiTree::PreOrder(BiNode *root) if(root==NULL) return; else{ return root; Release(root); root = Creat( ); coutdata PreOrder(root-lchild); void BiTree::yezi(BiNode *root,int n) if(root) { if(root-lchild==NULLroot-rchild==NULL) n++; yezi(root-lchild,n); yezi(root-rchild,n); BiNode* BiTree::Creat( ) BiNode *root; char ch; cinch; } if (ch==#) root = NULL; root = new BiNode; //生成一个结点 root-data=ch; root-lchild = Creat( ); //递归建立左子树 root-rchild = Creat( ); //递归建立右子树 } return root; void BiTree::Release(BiNode *root) if (root!= NULL){ Release(root-lchild); //释放左子树 Release(root-rchild); //释放右子树 delete root; void main() BiTree bt; //创建一棵树 BiNode *root = bt.Getroot( ); //获取指向根结点的指针 int n=0; bt.yezi(root,n); cout 5.运行与测试 非递归算法求叶子结点的个数 #include #include using namespace std; struct node node *lchild; node *rchild; node *root=NULL; void mid(node*root,int key=500) { int sum=0; stacks; while(NULL!=root || !s.empty()) { if(NULL!=root) { } else { // root=s.top(); coutdatalchild; } } } s.pop(); root=root-rchild; ++sum;

文档评论(0)

1亿VIP精品文档

相关文档