Binary Tree 2.0

Oh, winter's over half a blink of an eye. Wei think the data structure of the last semester of school is not ye (trained), the next semester there are two project na (trained, trained), so Wei again a lot to learn data structures, it started from the binary tree! (Although before exam week wrote a binary tree, but, uh, yeah, did not learn, therefore, to learn!)

First, let's look at the structure of the binary tree node :

template<class T>
struct binaryTreeNode
{
    T element;
    binaryTreeNode<T> *leftChild,//左儿子
                      *rightChild;//右儿子
    //构造函数
    binaryTreeNode()
    {
        leftChild=rightChild=NULL;
    }
    binaryTreeNode(const T& theElement)
    {
        element=theElement;
        leftChild=rightChild=NULL;
    }
    binaryTreeNode(const T& theElement,binaryTreeNode *theLeftChild,binaryTreeNode *theRightChild)
    {
        element=theElement;
        leftChild=theLeftChild;
        rightChild=theRightChild;
    }
};

The node has three constructors, corresponding to three different cases.

Then look at the binary tree abstract class :

template<class T>
class binaryTree
{
    virtual ~binaryTree(){}
    virtual bool empty() const =0;
    virtual int size() const =0;
    virtual void preOrder(void (*)(T*))=0;
    virtual void inOrder(void (*)(T*))=0;
    virtual void postOrder(void (*)(T*))=0;
    virtual void levelOrder(void (*)(T*))=0;
};

Since Wei too dishes, I do not understand the code book ,, so the school binary tree traversal from the network class. emm

Preorder
Here Insert Picture Description

//先序遍历
void preOrder(binaryTreeNode *BT)
{
    if(BT)
    {
        printf("%d",BT->element);
        preOrder(BT->leftChild);
        preOrder(BT->rightChild);
    }
}

Preorder
Here Insert Picture Description

//中序遍历
void inOrder(binaryTreeNode *BT)
{
    if(BT)
    {
        inOrder(BT->leftChild);
        printf("%d",BT->element);
        inOrder(BT->rightChild);
    }
}

Postorder
Here Insert Picture Description

//后序遍历
void postOrder(binaryTreeNode *BT)
{
    if(BT)
    {
        postOrder(BT->leftChild);
        postOrder(BT->rightChild);
        printf("%d",BT->element);
    }
}

Today on the first learned this ~

Published 32 original articles · won praise 12 · views 1362

Guess you like

Origin blog.csdn.net/qq_18873031/article/details/104127312