Recursive Implementation and non-Recursive Implementation of first-order traversal of Binary Trees

Source: Internet
Author: User

The following is a detailed analysis of Recursive Implementation and non-Recursive Implementation of the first-order traversal binary tree. If you need a friend, refer

1. Recursive Implementation of first-order traversal of Binary Trees
Thought: If the binary tree is empty, return. Otherwise
1) traverse the root node;
2) traverse the left subtree in sequence;
3) traverse the right subtree in sequence;

Code:

Copy codeThe Code is as follows:
Template <typename elemType>
Void PreOrder (nodeType <elemType> * root)
{
If (root = NULL)
Return;
Visit (root-> data); // visit the data
PreOrder (root-> lchild); // recursive call, first traverse the left subtree
PreOrder (root-> rchild); // recursive call, first traverse the right subtree
}


2. Non-Recursive Implementation of first-order traversal of Binary Trees
Idea: Non-recursive first-order traversal of a binary tree, first-order traversal idea: First let the root go into the stack, as long as the stack is not empty, you can do the pop-up operation, each time a node pops up, remember to add its left and right nodes to the stack and remember that the right subtree is in the advanced stack. This ensures that the right subtree is always under the left subtree.

Non-recursive algorithm IDEA for Traversing binary trees in the forward order
Create a Stack;
T points to the root;
When t is not empty or the Stack is not empty, repeat:
If t is not empty, access t, t is written into the stack; t is directed to the left child;
Otherwise, the elements at the top of the stack are included in t;
T points to the right child;
End

Copy codeThe Code is as follows:
Void PreOrder_Nonrecursive (BinaryTree T) // non-recursion of first-order traversal
{
If (! T) return;
Stack <BinaryTree> s;
S. push (T );
While (! S. empty ())
{
BinaryTree temp = s. top ();
Visit (temp-> data );
S. pop ();
If (temp-> rchild)
S. push (temp-> rchild );
If (temp-> lchild)
S. push (temp-> lchild );
}
}

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.