Build and traverse Binary Trees (2) (c ++ implementation)
[Goal]
Create a binary tree as shown below, and output the corresponding pre-order traversal, middle-order traversal, and post-order traversal.
[Code implementation]
// Binarytree. h # ifndef Binarytree_H # define Binarytree_Htemplate
Class Binarytree; template
Class TreeNode {friend class Binarytree
; Private: T data; TreeNode
* Rchild; // The right Pointer Points to the right subtree TreeNode
* Lchild; // The left Pointer Points to the left subtree}; template
Class Binarytree {public: Binarytree () {root = 0 ;}; void Creattree2 (); void Creattree2 (TreeNode
* Effectnode); // Use Pointer Reference to create a binary tree void Preorder (); void Preorder (TreeNode
* Currentnode); // preorder traversal void Inorder (); void Inorder (TreeNode
* Currentnode); // The void Postorder (); void Postorder (TreeNode
* Currentnode); // traverse private in the descending order: TreeNode
* Root;}; // -------------- first recursively create a binary tree -------- template
Void Binarytree
: Creattree2 () {Creattree2 (root);} template
Void Binarytree
: Creattree2 (TreeNode
* Effectnode) {// enter the node value (one character) in the binary tree in the First Order. The space character represents the empty tree, char ch, And if (ch = getchar ()) = '#') {currentnode = 0;} else {currentnode = new TreeNode
(); // Generate a new subtree currentnode-> data = ch; Creattree2 (currentnode-> lchild); // recursively create the left subtree Creattree2 (currentnode-> rchild ); // recursively create the right subtree} // ------ recursively implement the forward traversal of the Binary Tree ------ template
Void Binarytree
: Preorder () {cout <pre-order traversal (root-> left-> right):; Preorder (root);} template
Void Binarytree
: Preorder (TreeNode
* Currentnode) {if (currentnode) {cout <
Data <; Preorder (currentnode-> lchild); Preorder (currentnode-> rchild); }}// ------ recursively implement ordinal traversal of Binary Trees ------ template
Void Binarytree
: Inorder () {cout <central order traversal (left-> root-> right):; Inorder (root);} template
Void Binarytree
: Inorder (TreeNode
* Currentnode) {if (currentnode) {Inorder (currentnode-> lchild); cout <
Data <; Inorder (currentnode-> rchild) ;}}// ------ recursively implement post-sequential traversal of Binary Trees ------ template
Void Binarytree
: Postorder () {cout <post-order traversal (left-> right-> root):; Postorder (root);} template
Void Binarytree
: Postorder (TreeNode
* Currentnode) {if (currentnode) {Postorder (currentnode-> lchild); Postorder (currentnode-> rchild); cout <
Data <<}}# endif
//main.cpp#include Binarytree.h#include
using namespace std;int main(){ Binarytree
Tree1; Tree1.Creattree2(); Tree1.Preorder(); cout<
[Result diagram]