Description
Define the type for binary trees as follow:
template struct BinaryNode{
T elem;
BinaryNode *left;
BinaryNode * right;
BinaryNode(T d, BinaryNode *l=NULL, BinaryNode *r=NULL):elem(d),left(l),right(r){};
};
Your task is to implement binary tree traversal using both recursion and non-recursion.
// root is a pointer to the root of the binary tree.
template
void inorder_recursive(BinaryNode* root, void (*visit)(T &x))
// root is a pointer to the root of the binary tree.
template
void inorder(BinaryNode* root, void (*visit)(T &x))
Just submit the inorder_recursive function and inorder function. Don’t submit the BinaryNode definition and the main function.
Input
None
Output
None
Sample Input
None.
Sample Output
None.
Hint
Submitt both of your implementations, including the definition of BinaryNode.
Your task is to implement binary tree traversal using both recursion and non-recursion.
// root is a pointer to the root of the binary tree.
template <typename T>
void inorder_recursive(BinaryNode<T>* root, void (*visit)(T &x))
{
if(root)
{
inorder_recursive(root->left, visit);
visit(root->elem);
inorder_recursive(root->right, visit);
}
}
template <typename T>
void inorder(BinaryNode<T>* root, void (*visit)(T &x))
{
BinaryNode<T>* pCur = root;
BinaryNode<T>* nodePop;
stack<BinaryNode<T>*> nodeStack;
while(pCur || !nodeStack.empty())
{
if(pCur->left)
{
nodeStack.push(pCur);
pCur = pCur->left;
}
else
{
visit(pCur->elem);
pCur = pCur->right;
while(!pCur && !nodeStack.empty())
{
nodePop = nodeStack.top();
nodeStack.pop();
visit(nodePop->elem);
pCur = nodePop->right;
}
}
}
}
// // root is a pointer to the root of the binary tree.
// template <typename T>
// void inorder(BinaryNode<T>* root, void (*visit)(T &x))
// {
// if(root)
// {
// BinaryNode<T>* pCur = root;
// BinaryNode<T>* nodePop;
// stack<BinaryNode<T>*> nodeStack;
// while(pCur || !nodeStack.empty())
// {
// nodeStack.push(pCur);
// if(pCur->left == NULL)
// {
// pCur = pCur->right;
// while(!pCur && !nodeStack.empty())
// {
// nodePop = nodeStack.top();
// nodeStack.pop();
// visit(nodePop->elem);
// pCur = nodePop->right;
// }
// } else
// pCur = pCur->left;
// }
// }
// }
// root is a pointer to the root of the binary tree.