Traversal of the "Daily algorithm" binary tree

Source: Internet
Author: User

two fork Tree features
    1. Each node has a maximum of two subtrees trees;
    2. Binary tree is ordered, that is, to distinguish the order of the left and right sub-trees.

Complete binary Tree

    1. Leaf nodes can only be in the bottom two layers, and the bottom of the leaf nodes are concentrated on the left side of the binary tree continuous position.

    2. If there is a node with a degree of 1, there may only be one, and the node only has a left child.

Two fork Tree implementation

This is only a two-fork list implementation, using C + +.

Template<class DataType>struct Binode{DataType  data;    Binode<DataType> *lchild, *rchild; };Template<class DataType>class Bitree{public:Bitree(){root =creat(root);} ~Bitree(){Release(root);} voidPreorder(){Preorder(root);} voidinorder(){inorder(root);} voidPostorder(){Postorder(root);} voidLevelorder();p rivate:Binode<DataType> *root;Binode<DataType> *creat(binode<DataType> *bt); voidRelease(binode<DataType> *bt); voidPreorder(binode<DataType> *bt); voidinorder(binode<DataType> *bt); voidPostorder(binode<DataType> *bt);};

Contribution: The creat function can be called recursively to implement, note for parameters

BiNode<DataType> *bt

BT is a formal parameter, the modification to it only takes effect in the function body, if you want to modify the passed in pointer, you can use the reference:

BiNode<DataType> * &bt

destructor: When releasing a node, it is necessary to release its left and right subtree, so it can be released using the method of post-post traversal.

Pre-sequence traversal

The pre-sequence traversal accesses the root node and then accesses the left and right subtrees, and its recursive implementation:

void BiTree<DataType>::PreOrder(BiNode<DataType>*bt){    if (NULL== bt)        return ;    << bt->data<<‘ ‘;    PreOrder(bt->lchild);    PreOrder(bt->rchild);}

In fact, the process of our recursion is as follows:

Access node, left-to-right access node, to the left, until the left node is null, then returns the parent node of the null node, and accesses the parent node's son, continuing to repeat access to the node, to the left ... The process.

So we can use a stack to write a non-recursive version:

void BiTree<DataType>::PreOrder(BiNode<DataType> *bt){    stack<BiNode<DataType> *> s;    while (bt || !s.empty())    {        while (bt)        {            cout‘ ‘;            s.push(bt);            bt = bt->lchild;        }        if (!s.empty())        {            bt = s.top();            s.pop();            bt = bt->rchild;        }    }}
Middle Sequence Traversal

The middle sequence traversal accesses the left subtree first, then accesses the root node, and finally accesses the right subtree, which is implemented recursively:

void BiTree<DataType>::InOrder(BiNode<DataType>*bt){    if (NULL== bt)        return ;    InOrder(bt->lchild);    << bt->data<<‘ ‘;    InOrder(bt->rchild);}

A non-recursive version of a middle-order traversal is very similar to a pre-order traversal:

void BiTree<DataType>::InOrder(BiNode<DataType> *bt){    stack<BiNode<DataType> *> s;    while (bt || !s.empty())    {        while (bt)        {            s.push(bt);            bt = bt->lchild;        }        if (!s.empty())        {            bt = s.top();            s.pop();            cout‘ ‘//将访问移到这里            bt = bt->rchild;        }    }}
Post-post traversal

The sequential traversal first accesses the left subtree, then accesses the right subtree, and finally accesses the root node, its recursive implementation:

void BiTree<DataType>::PostOrder(BiNode<DataType>*bt){    if (NULL== bt)        return ;    PostOrder(bt->lchild);    PostOrder(bt->rchild);    << bt->data<<‘ ‘;}

The non-recursive version of the subsequent traversal is a bit more difficult.

For a node, it needs to stack two times, out of the stack two times:
First out of the stack: only through the left dial hand tree, the right subtree has not been traversed, using the top node of the stack to find its right sub-tree (equivalent to the stack and into the stack), ready to traverse its right subtree.
Second out stack: After traversing the right subtree, the node is out of the stack and accessed.

To distinguish two times from the same node, we set flag flags:

Flag=1, indicates that the first time out of the stack, only through the left dial hand tree, the node can not access;
Flag=2, indicates the second time out of the stack, traversing the right subtree, the node can access;

For the root node BT, there are two scenarios:

    1. BT is not NULL, then BT and flag (set to 1) into the stack, traversing its left subtree;
    2. BT is NULL, if the stack is empty, indicating the end of the entire traversal, if the stack is not empty, the top node of the stack of left subtree or right subtree traversal completed, at this time, if the top element of the stack flag=1, indicating that just traversed the left dial hand tree, so modify the flag=2, traverse the right subtree, if the top of the stack flag=2, indicating The top element of the output stack.
voidBitree<datatype&gt::P ostorder (binode<datatype> *bt) { Stack<BiNode<DataType>*> s; Stack<int>S_flag; while(BT | |!s.empty ()) { while(BT)            {S.push (BT); S_flag.push (1);        BT = bt->lchild; } while(!s.empty () &&2= = S_flag.top ()) {BT = S.top ();            S.pop (); S_flag.pop ();cout<< Bt->data <<"'; }if(!s.empty ())            {S_flag.pop (); S_flag.push (2);        BT = S.top ()->rchild; }    }}
sequence Traversal

The sequence traversal is a layer of access, a node is accessed, then in the next layer, its son node will be accessed, for the same layer of two nodes A, b,a on the left of B, then A's son node before B's son node is accessed.

In short, the first access node, the left and right children must first access, so we can use a queue to maintain the process:

The root node is enqueued and then
1. Remove an element from the queue header to do the following:
2. Access to the element;
3. If the left and right child of the node is not empty, the child will be in the queue;
4. Go back to 1 until the queue is empty.

void BiTree<DataType>::LevelOrder(){    queue<BiNode<DataType> *> q;    if (root)        q.push(root);    while (!q.empty())    {        BiNode<DataType> *cur = q.top();        q.pop();        cout‘ ‘;        if (cur->lchild)            q.push(cur->lchild);        if (cur->rchild)            q.push(cur->rchild);    }}

Make a little progress every day, Come on!

(●’?’●)

I have limited level, such as the content of the article has errors and omissions, please point out the reader, thank you!

Traversal of the "Daily algorithm" binary tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.