码迷,mamicode.com
首页 > 编程语言 > 详细

c++中树的拷贝构造函数的迭代实现

时间:2016-09-08 23:20:07      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:

具体思想是通过遍历目标树,保存对应的左右孩子节点位置。以按顺序拷贝对应位置的内容。

这里用先序遍历的原因是为了当要取等待拷贝的节点的左右孩子的位置,可以保证此节点存在。避免访问NULL使程序跳出。

 

 

  1. template<typename T>
  2. inline BinTree<T>::BinTree(BinTree & binTree)
  3. {
  4.     BinNodePosi(T) otherTreeNode;
  5.     stack<BinNodePosi(T)>otherBinNodeStack;
  6.     BinNode<T>** selfTreeNode;
  7.     stack<BinNode<T>**>selfBinNodeStack;
  8.     selfBinNodeStack.push(&_root);
  9.     otherBinNodeStack.push(binTree._root);
  10.     while (!otherBinNodeStack.empty())
  11.     {
  12.         selfTreeNode = selfBinNodeStack.top(); selfBinNodeStack.pop();
  13.         otherTreeNode = otherBinNodeStack.top(); otherBinNodeStack.pop();
  14.         *selfTreeNode = new BinNode<T>(otherTreeNode->data, otherTreeNode->parent);
  15.         if (otherTreeNode->rc)
  16.         {
  17.             otherBinNodeStack.push(otherTreeNode->rc);
  18.             selfBinNodeStack.push(&((*selfTreeNode)->rc));
  19.         }
  20.         if (otherTreeNode->lc)
  21.         {
  22.             otherBinNodeStack.push(otherTreeNode->lc);
  23.             selfBinNodeStack.push(&((*selfTreeNode)->lc));
  24.         }
  25.     }
  26. }

c++中树的拷贝构造函数的迭代实现

标签:

原文地址:http://www.cnblogs.com/qzy1015004506/p/5854782.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!