【工程】二叉樹已知前序/中序的順序,構造樹的遞迴等實現

來源:互聯網
上載者:User

文章中的二叉樹原型為 《Data Structures, Algorithms, & Applications in C++》, 1nd Edition中的樹類。

要求在源檔案的基礎上 實現以下三個操作:

【1】給出前序走訪和中序遍曆結果,構造樹。

【2】給出計算葉子節點數目的函數。

【3】交換樹中的左右所有節點。

需要用到的主要函數(異常拋出\鏈表隊列之類與主題沒啥關係的請查書):

遍曆尋找函數:

    BinaryTree<char> MakeTree2(string InOrder, string PreOrder){BinaryTree<char> tree;if(InOrder.empty()){tree.root = 0;return tree;}char RootValue;RootValue = PreOrder[0];//根結點的值//計算左右子樹中結點數size_t pos,LeftChildSize, RightChildSize;pos = InOrder.find(RootValue);LeftChildSize = pos;RightChildSize = InOrder.size() - pos - 1;string LeftInOrder, LeftPreOrder, RightInOrder, RightPreOrder;//原函數不變LeftInOrder = InOrder.substr(0, LeftChildSize);RightInOrder = InOrder.substr(pos + 1, RightChildSize);LeftPreOrder = PreOrder.substr(1,LeftChildSize+1);RightPreOrder =PreOrder.substr(LeftChildSize+1,RightChildSize+1);                                               BinaryTree<char> left,right;left = MakeTree2(LeftInOrder,LeftPreOrder);right = MakeTree2(RightInOrder,RightPreOrder);tree.root = new BinaryTreeNode<char>(RootValue);    tree.root->LeftChild = left.root;    tree.root->RightChild = right.root;    left.root = right.root = 0;return tree;}    

BinaryTree.h

#include<iostream>#include "LinkedQueue.h"#include "binaryTreeNode.h"#include "myexception.h"#include <string>#ifndef _BinaryTree#define _BinaryTreeint _count;template<class T>class BinaryTree {   public:      BinaryTree() {root = 0;};      ~BinaryTree(){};       bool IsEmpty() const        {return ((root) ? false : true);}      bool Root(T& x) const;      void MakeTree(const T& element,           BinaryTree<T>& left, BinaryTree<T>& right);      void BreakTree(T& element, BinaryTree<T>& left,                    BinaryTree<T>& right);      void PreOrder(void(*Visit)(BinaryTreeNode<T> *u))           {PreOrder(Visit, root);}      void InOrder(void(*Visit)(BinaryTreeNode<T> *u))           {InOrder(Visit, root);}      void PostOrder(void(*Visit)(BinaryTreeNode<T> *u))           {PostOrder(Visit, root);}  void LevelOrder(void(*Visit)(BinaryTreeNode<T> *u));  void ExChange(BinaryTreeNode<T> *u);      void PreOutput() {PreOrder(Output, root); cout << endl;}      void InOutput() {InOrder(Output, root); cout << endl;}      void PostOutput() {PostOrder(Output, root); cout << endl;}      void LevelOutput() {LevelOrder(Output); cout << endl;}      void Delete() {PostOrder(Free, root); root = 0;}      int Height() const {return Height(root);}      int Size()         {_count = 0; PreOrder(Add1, root); return _count-1;}  //修改 葉子節點個數  int SizeLeaf(BinaryTreeNode<T> *root)      {  if(root==NULL)return 0;  else if(root->LeftChild==NULL && root->RightChild==NULL)return 1;  else  return SizeLeaf(root->LeftChild)+SizeLeaf(root->RightChild);  }    //自己添加的函數,P31--1  bool Compare(BinaryTreeNode<T> *X,BinaryTreeNode<T> *Y)  {  if(!Y && !X)return true;  if((!(!Y && !X)) &&((!Y)||(!X)) || Y->data != X->data)  return false;  if(Compare(X->LeftChild, Y->LeftChild) && Compare(X->RightChild, Y->RightChild))  return true;  else  return false;  }     BinaryTreeNode<T> *root;    private:           void PreOrder(void(*Visit)        (BinaryTreeNode<T> *u), BinaryTreeNode<T> *t);      void InOrder(void(*Visit)        (BinaryTreeNode<T> *u), BinaryTreeNode<T> *t);      void PostOrder(void(*Visit)        (BinaryTreeNode<T> *u), BinaryTreeNode<T> *t);      static void Free(BinaryTreeNode<T> *t) {delete t;}      static void Output(BinaryTreeNode<T> *t)                  {cout << t->data << ' ';}      static void Add1(BinaryTreeNode<T> *t) {_count++;}      int Height(BinaryTreeNode<T> *t) const;};template<class T>bool BinaryTree<T>::Root(T& x) const{   if (root) {x = root->data;              return true;}   else return false; }template<class T>void BinaryTree<T>::MakeTree(const T& element,          BinaryTree<T>& left, BinaryTree<T>& right){   root = new BinaryTreeNode<T>              (element, left.root, right.root);     left.root = right.root = 0;}template<class T>void BinaryTree<T>::BreakTree(T& element,       BinaryTree<T>& left, BinaryTree<T>& right){   if (!root) throw BadInput();    element = root->data;   left.root = root->LeftChild;   right.root = root->RightChild;   delete root;   root = 0;}//交換樹的左右子節點.template <class T> void BinaryTree<T>::ExChange(BinaryTreeNode<T> *u){   BinaryTreeNode<T> *temp;   temp = root;   if(u)   {   temp=u->LeftChild;   (u)->LeftChild=(u)->RightChild;   (u)->RightChild=temp;   ExChange((*u).LeftChild);   ExChange((*u).RightChild);   }} template<class T> void BinaryTree<T>::PreOrder(               void(*Visit)(BinaryTreeNode<T> *u),                         BinaryTreeNode<T> *t){   if (t)    {   Visit(t);      PreOrder(Visit, t->LeftChild);      PreOrder(Visit, t->RightChild);   }} template <class T> void BinaryTree<T>::InOrder(            void(*Visit)(BinaryTreeNode<T> *u),                         BinaryTreeNode<T> *t){   if (t) {   InOrder(Visit, t->LeftChild);      Visit(t);      InOrder(Visit, t->RightChild);          }} template <class T> void BinaryTree<T>::PostOrder(            void(*Visit)(BinaryTreeNode<T> *u),                         BinaryTreeNode<T> *t){   if (t) {   PostOrder(Visit, t->LeftChild);           PostOrder(Visit, t->RightChild);           Visit(t);           }} template <class T> void BinaryTree<T>::LevelOrder(           void(*Visit)(BinaryTreeNode<T> *u)){   LinkedQueue<BinaryTreeNode<T>*> Q;   BinaryTreeNode<T> *t;   t = root;   while (t) {      Visit(t);      if (t->LeftChild) Q.Add(t->LeftChild);      if (t->RightChild) Q.Add(t->RightChild);      try {Q.Delete(t);}      catch (OutOfBounds) {return;}      }}template <class T>int BinaryTree<T>::Height(BinaryTreeNode<T> *t) const{   if (!t) return 0;                 int hl = Height(t->LeftChild);    int hr = Height(t->RightChild);   if (hl > hr) return ++hl;   else return ++hr;}#endif

BinaryTreeNode.h,沒改。。

#ifndef BinaryNode#define BinaryNodetemplate <class T> class BinaryTree;template <class T>class BinaryTreeNode {   friend BinaryTree<T>;   public:      BinaryTreeNode() {LeftChild = RightChild = 0;}      BinaryTreeNode(const T& e)            {data = e; LeftChild = RightChild = 0;}      BinaryTreeNode(const T& e, BinaryTreeNode *l,                     BinaryTreeNode *r)       {data = e; LeftChild = l; RightChild = r;}      T data;      BinaryTreeNode<T> *LeftChild,                          *RightChild; };#endif

測試檔案:

#include <iostream>#include <string>#include "BinaryTree.h"#include "myexception.h"#include "BinaryTreeNode.h"using namespace std;int count = 0;BinaryTree<int> a,x,y,z,q,r,s;int main(){y.MakeTree(3,a,a);x.MakeTree(4,a,a);z.MakeTree(5,y,x);cout<<"交換前:";z.PreOutput();//交換測試z.ExChange(z.root);cout<<"交換後:";z.PreOutput();//個數測試cout<<"葉子節點個數:"<<z.SizeLeaf(z.root)<<endl;//聲明一個變數BinaryTree<char> p;//qianxu="111",zhongxu="111";/*string zhongxu="1234";string qianxu="4321";*//*string zhongxu="312";string qianxu="132";*/string zhongxu="32145";string qianxu="12345";p=MakeTree2(zhongxu,qianxu);cout<<"Add之後 前序的結果:";p.PreOutput();cout<<endl;   system("pause");   return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.