遞迴二叉樹建立和遍歷及深度計算
阿新 • • 發佈:2019-01-25
上篇咱們說到二叉樹的一種建立方法及三種遍歷方法的遞迴非遞迴演算法。這篇換了一種新的建立方法,用先根遍歷遞迴的思路建立二叉樹,用遞迴的方法計算深度,用中根遞迴和非遞迴方法遍歷整個二叉樹。
BinaryTree.h
BinaryTree.cpp//二叉樹的建立和遍歷 #ifndef BINARYTREE_H_ #define BINARYTREE_H_ #include <iostream> typedef int T; struct Node { T data; Node *lch; Node *rch; }; class BinaryTree { private: Node *root; Node *create_bt(); void inorder(Node *p); int predepth(Node *t); void destroy(Node *p); int max(int x, int y); public: BinaryTree() { root=NULL; } ~BinaryTree() { destroy(root); } void create(); void inorder() { inorder(root); } void inorderz();//中根非遞迴遍歷 int predepth(){return predepth(root);}//求二叉樹的深度遞迴函式 }; #endif
main.cpp#include "BinaryTree.h" #include <iostream> #include <stack> using namespace std; void BinaryTree::create() { cout<<"請按照二叉樹先根次序,且將空孩子置為0,組織資料"<<endl; cout<<"每次輸入結點的資料,假設是一棵3個結點的滿二叉樹。"<<endl; cout<<"那麼輸入應是:11 22 0 0 33 0 0"<<endl; root=create_bt(); } Node *BinaryTree::create_bt() { Node *t; int e; cout<<"輸入結點的值:"; cin>>e; if(e==0) t=NULL; else { t=new Node; t->data=e; t->lch=create_bt(); t->rch=create_bt(); } return t; } void BinaryTree::inorderz()//中根非遞迴遍歷 { Node *p=root; Node *q; stack<Node *> S; do { while(p!=NULL) { S.push(p); p=p->lch; } p=S.top(); S.pop(); cout<<p->data<<" "; p=p->rch; }while(!(S.empty() && p==NULL)); } void BinaryTree::inorder(Node *p) { if(p!=NULL) { inorder(p->lch); cout<<p->data<<" "; inorder(p->rch); } } int BinaryTree::predepth(Node *t) { if(t!=NULL) { return 1+max(predepth(t->lch),predepth(t->rch)); } else return 0; } int BinaryTree::max(int x, int y) { return (x>=y?x:y); } //用遞迴法刪除二叉樹的所有結點 void BinaryTree::destroy(Node *p) { if(p!=NULL) { destroy(p->lch); destroy(p->rch); } delete p; }
結果為:#include <iostream> #include "BinaryTree.h" using namespace std; int main() { BinaryTree BT; BT.create(); cout<<"中根遞迴遍歷:"<<endl; BT.inorder(); cout<<"中根非遞迴遍歷:"<<endl; BT.inorderz(); cout<<endl<<"二叉樹的深度為:"<<BT.predepth()<<endl; system("pause"); return 0; }