Tree - 0004

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值