题目.
二叉树(三叉链表存储)
二叉树的成员函数,不使用栈的非递归算法(迭代)
1.BinaryTree(T prelist[], int n)以标明空子树的先根序列构造二叉树(不使用栈的非递归算法)
2.BinaryTree(BinaryTree<T> &bitree)深拷贝,不使用栈的非递归算法。
template <class T>
class Node
{
public:
T data;
Node<T> *left,*right,*parent;
Node(T data, Node<T> *parent=NULL,Node<T> *left=NULL, Node<T> *right=NULL)
{
this->data = data;
this->parent = parent;
this->left = left;
this->right = right;
}
bool isLeaf()
{
return this->left==NULL && this->right==NULL;
}
};
template <class T>
BinaryTree<T>::BinaryTree(T prelist[], int n) //BinaryTree(T prelist[], int n)以标明空子树的先根序列构造二叉树(不使用栈的非递归算法)
{
int i;
Node<T> *p = NULL;
this->root = new Node<T>(prelist[0]);
p = this->root;
for( i = 1; i < n ;i++)
{
while(p->right!=NULL)
p=p->parent;
if( prelist[i] != NULL)
{
if( prelist[i-1]== NULL)
{
p = new Node<T>(prelist[i],p);
p->parent->right = p;
}
else
{
p = new Node<T>(prelist[i],p);
p->parent->left = p;
}
}
else if(prelist[i-1] == NULL && prelist[i] == NULL )
p = p->parent;
}
}
template<class T>
BinaryTree<T>::BinaryTree( BinaryTree<T> &bitree )////10-16 BinaryTree(BinaryTree<T> &bitree)深拷贝,不使用栈的非递归算法。
{
Node<T> *p = bitree.root;
Node<T> *q = NULL;
this->root = new Node<T>( p->data );
q = this->root;
while(p != NULL)
{
while( p->left != NULL && q->left == NULL )
{
p = p->left;
q = new Node<T>(p->data,q);
q->parent->left=q;
}
if( p->right != NULL && q->right == NULL )
{
p = p->right;
q = new Node<T>(p->data,q);
q->parent->right = q;
}
else
{
while(p->parent != NULL && p->parent->right == p)
{
p = p->parent;
q = q->parent;
}
p = p->parent;
q = q->parent;
}
}
}
一个在努力中的未来程序员
,如果有更好的算法,欢迎评论。