Recursive and non-recursive Problems

Source: Internet
Author: User
Assume that the structure of a tree node is given: struct node {int data; struct node * left; struct node * right;} typedef strcut node * tree tells you to write code for Recursive tree traversal, in fact, it is very simple to traverse the following in the middle order: void traverse (tree T, (* visit) (INT) {If (! T) {traverse (t-> left, visit); (* visit) (t-> data); traverse (t-> right, visit );}} if you want to write non-recursive traversal, you have to worry about it. The most important thing to write this non-recursive traversal is to understand what happened in the recursion process, and try to simulate the entire process through iteration. # Include <stack> using namespace STD; void inorder_traverse (tree T, void (* visit) (INT) {tree P = T; stack <node *> S; while (p |! S. empty () {While (p) {S. push (p); P = p-> left;} p = S. pop (); (* visit) (p-> data); P = p-> right ;}}

Why do we have to write a non-recursive code?

I thought that non-recursion can avoid the time-space consumption caused by recursive calls, but I always felt that this reason was far-fetched.

Today I found a more convincing reason. The tree structure can be used to implement the container class, so we need to generate an iterator to traverse the entire container,

Therefore, we must use a non-recursive algorithm to return an element after each call to next and point the pointer to the next element.

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.