Directly run the Code:
/* Implement the linked list of a binary tree: and three traversal methods: author: unparalleled Date: 2014-5-28Version: 2.0 */# include
# Include
Typedef int T; // the data Type of the node in the tree: using namespace std; class BiTree {private: struct BiNode {T data; BiNode * lchild, * rchild; BiNode (T d) {data = d; lchild = nullptr; rchild = nullptr ;}}; BiNode * root; public: BiTree () {// root = root-> rchild = nullptr; root = nullptr ;}~ BiTree () {}// use recursion to create a binary tree // create a binary tree rule/* List pointer to write bool addBiNode (BiNode ** nodeRoot, T d) {if (* nodeRoot = nullptr) {BiNode * p = new BiNode (d); * nodeRoot = p; cout <
Data <"insert success! "<
Data) {// recursive addBiNode (& (* nodeRoot)-> lchild), d);} else if (* nodeRoot! = Nullptr & d> (* nodeRoot)-> data) {// recursive addBiNode (& (* nodeRoot)-> rchild), d );} else {cout <"the data already exists in the tree" <
Data <"insert success! "<
Data) {// recursive addBiNode (nodeRoot-> lchild, d);} else if (nodeRoot! = Nullptr & d> (nodeRoot)-> data) {// recursive addBiNode (nodeRoot-> rchild, d) to the right subtree );} else {cout <"the data already exists in the tree" <
Data <";}/// recursive traversal is used. The three traversal principles are the same // forward traversal. The first root traversal is void PreOrderTraverse (const BiNode * nodeRoot) const {if (nodeRoot! = Nullptr) Visit (nodeRoot); if (nodeRoot-> lchild! = Nullptr) PreOrderTraverse (nodeRoot-> lchild); if (nodeRoot-> rchild! = Nullptr) PreOrderTraverse (nodeRoot-> rchild);} // The root traversal void InOrderTraverse (const BiNode * nodeRoot) const {if (nodeRoot-> lchild! = Nullptr) InOrderTraverse (nodeRoot-> lchild); if (nodeRoot! = Nullptr) // Visit (nodeRoot) when the left subtree of the vertex is empty; if (nodeRoot-> rchild! = Nullptr) InOrderTraverse (nodeRoot-> rchild);} // The void PostOrderTraverse (const BiNode * nodeRoot) const {if (nodeRoot-> lchild! = Nullptr) PostOrderTraverse (nodeRoot-> lchild); if (nodeRoot-> rchild! = Nullptr) PostOrderTraverse (nodeRoot-> rchild); if (nodeRoot! = Nullptr) Visit (nodeRoot );}};
Test code:
Int main () {BiTree B; // B. addBiNode (& B. root, 50); // set the root node value // write the second-level pointer B. addBiNode (B. getRoot (), 50); // pointer reference method int I; int arr [9] = {30, 40, 35, 27, 999,-}; bool flag = true; while (flag) {flag =! Flag; // cout <"enter a number (input-999 will exit:"; // cin> I; for (int j = 0; j <9; j ++) {I = arr [j]; if (I =-999) break; B. addBiNode (B. getRoot (), I);} // B. addBiNode (& B. root, I);} B. traverse (B. getPtrToRoot (), "PreOrderTraverse"); B. traverse (B. getPtrToRoot (), "InOrderTraverse"); B. traverse (B. getPtrToRoot (), "PostOrderTraverse"); cin. get (); system ("pause"); return 0 ;}
Test results: (Note that the input sequence is different from the tree generated at the same time)