Source of constructors.cpp


  1: //  Created by Frank M. Carrano and Timothy M. Henry.
  2: //  Copyright (c) 2017 Pearson Education, Hoboken, New Jersey.

  4: template<class ItemType>
  5: BinaryNodeTree<ItemType>::BinaryNodeTree() : rootPtr(nullptr)
  6: {
  7: }  // end default constructor

  9: template<class ItemType>
 10: BinaryNodeTree<ItemType>::
 11: BinaryNodeTree(const ItemType& rootItem)
 12:       : rootPtr(std::make_shared<BinaryNode<ItemType>>(rootItem, nullptr, nullptr))
 13: {
 14: } // end constructor

 16: template<class ItemType>
 17: BinaryNodeTree<ItemType>::
 18: BinaryNodeTree(const ItemType& rootItem,
 19:                const std::shared_ptr<BinaryNodeTree<ItemType>> leftTreePtr,
 20:                const std::shared_ptr<BinaryNodeTree<ItemType>> rightTreePtr)
 21:       : rootPtr(std::make_shared<BinaryNode<ItemType>>(rootItem,
 22:                                                        copyTree(leftTreePtr–>rootPtr),
 23:                                                        copyTree(rightTreePtr–>rootPtr))
 24: {
 25: } // end constructor

 27: template<class ItemType>
 28: BinaryNodeTree<ItemType>::
 29: BinaryNodeTree(const BinaryNodeTree<ItemType>& treePtr)
 30: {
 31:    rootPtr = copyTree(treePtr.rootPtr);
 32: }  // end copy constructor

 34: template<class ItemType>
 35: std::shared_ptr<BinaryNode<ItemType>> BinaryNodeTree<ItemType>::copyTree(
 36:      const std::shared_ptr<BinaryNode<ItemType>> oldTreeRootPtr) const
 37: {
 38:    std::shared_ptr<BinaryNode<ItemType>> newTreePtr;
 39:    
 40:    // Copy tree nodes during a preorder traversal
 41:    if (oldTreeRootPtr != nullptr)
 42:    {
 43:       // Copy node
 44:       newTreePtr = std::make_shared<BinaryNode<ItemType>>(oldTreeRootPtr–>getItem(),
 45:                                                           nullptr, nullptr);
 46:       newTreePtr–>setLeftChildPtr(copyTree(oldTreeRootPtr–>getLeftChildPtr()));
 47:       newTreePtr–>setRightChildPtr(copyTree(oldTreeRootPtr–>getRightChildPtr()));
 48:    }  // end if
 49:    // Else tree is empty (newTreePtr is nullptr)
 50:    
 51:    return newTreePtr;
 52: }  // end copyTree