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 );
}
}