Binary Tree iterator Algorithm

Source: Internet
Author: User

The first, middle, and subsequent traversal of a binary tree isAlgorithmAnd the basic problems in the data structure, the recursive binary tree traversal algorithm is also a typical application of recursion.

Assume that the Binary Tree node is defined as follows:

 
Struct node {int value; node * left; node * right ;}

Recursive Traversal Algorithm in the middle order:

 
// C ++ void inorder_traverse (node * node) {If (null! = Node-> left) {inorder_traverse (node-> left);} do_something (node); If (null! = Node-> right) {inorder_traverse (node-> right );}}

The pre-order and post-order traversal algorithms are similar.

However, Traversal Algorithms alone are not enough. In many applications, we also need to abstract the traversal itself. If there is a sum function, we hope it can be applied to different data structures, such as linked lists, arrays, and Binary Trees. At this time, we can abstract the concept of iterator, throughThe iterator decouples the algorithm from the data structure.So that the general algorithm can be applied to different types of data structures. We can define the sum function:

 
Int sum (iterator it)

As a linear structure, the linked list has a simple and intuitive implementation of its iterator, while the implementation of the Binary Tree iterator is not so easy. We cannot directly convert recursive traversal into an iterator. This is because the recursive traversal process of Binary Trees is automatically implemented by the compiler on the call stack,ProgramMembers lack sufficient control over the process. In this case, if we can control the inbound and outbound stack of the entire call stack, will it achieve the purpose of control? Let's take a look at the non-recursive algorithm of binary tree traversal:

 
// C ++ void inorder_traverse_nonrecursive (node * node) {stack; do {// node indicates the subtree to be processed, and the left child is pressed down to the stack layer by layer, correspond to the left subtree of the recursive algorithm recursion while (null! = Node) {stack. push (node); node = node-> left;} do {node * Top = stack. top (); stack. pop (); // The top of the pop-up stack. The function corresponding to the recursive algorithm returns do_something (top); If (null! = Top-> right) {node = Top-> right; // set the current subtree to the right child of the node that has just been traversed, recursive break corresponding to the right subtree of the recursive algorithm;} while (! Stack. Empty ();} while (! Stack. Empty ());}

Through the stack-based non-recursive algorithm, we have obtained control over the traversal process. How can we encapsulate it as an iterator? The key here is that the process of understanding traversal is represented by the stack state, so it is clear that the iterator should contain a stack structure, and each iteration is a stack operation. Assume that the iterator interface is:

Class iterator {public: Virtual node * Next () = 0 ;};

The following is an implementation of the ordinal traversal iterator in a binary tree:

 
// C ++ class inorderiterator: Public iterator {public: inorderiterator (node * node) {node * Current = node; while (null! = Current) {mstack. push (current); current = Current-> left;} virtual node * Next () {If (mstack. empty () {return NULL;} node * Top = mstack. top (); mstack. pop (); If (null! = Top-> right) {node * Current = Top-> right; while (null! = Current) {mstack. Push (current); current = Current-> left ;}} return top;} PRIVATE: STD: Stack <node *> mstack ;};

Next, let's take a look at the time and space complexity of this iterator. Obviously, since the stack needs to store at most all nodes, the space complexity is O (n. So what is the time complexity? One next () call can also perform n stack operations at most, and the entire traversal process requires n next () calls (), so is the time complexity of the entire iterator O (N ^ 2? The answer is no! Because each node only goes into and out of the stack once, the time complexity of the entire iteration process is still O (n ). In fact, this is exactly the same as the time-space complexity of recursive traversal.

In addition to the above explicit use of stack ControlCodeIn addition to the execution sequence, there are more direct methods in languages that support yield semantics (such as C # And Python. The following Python Implementation of sequential traversal based on Yield Binary Tree:

 
// Pythondef inorder (t): If T: for X in inorder (T. Left): yield x yield T. Label for X in inorder (T. Right): yield x

A common explanation of the difference between yield and return is that the system retains the function call status when yield returns. The next time this function is called, it will continue to be executed from the last execution point, this is a process control semantics that is completely different from Stack semantics. We know that python interpreters are written in C, but C does not support yield semantics. How does the interpreter support yield? With the above experience of transforming recursive traversal into iterative traversal, I believe you have guessed that the python interpreter must have performed some transformation on the Yield code. If you can implement recursion and non-recursion, try to write a Compilation Program to convert yield code into non-yield code.

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.