怎么用非递归算法创建二叉树
收起
知与谁同
2018-07-20 19:47:19
1734
0
1
条回答
写回答
取消
提交回答
-
代码:
void Tree<T>::creat_tree(TreeNode<T> * &pointer)
{
//非递归实现对森林的赋值;*******************************
T temp;
stack<TreeNode<T> *> creat_help;
cin>>temp;
if(temp=='#')
{
pointer=NULL;
return;
}
pointer=new TreeNode<T>;
pointer->get_val()=temp;
creat_help.push(pointer);
TreeNode<T> * temp_pointer=pointer;
int tag=0; //标志位,值为0,表示处理结点的左孩子,值为1,表示处理结点的右孩子;
while(cin>>temp)
{
if(temp!='#')
{
if(tag==0)
{
temp_pointer->get_LeftMostcld()=new TreeNode<T>;
temp_pointer->get_LeftMostcld()->get_val()=temp;
creat_help.push(temp_pointer->get_LeftMostcld());
temp_pointer=temp_pointer->get_LeftMostcld();
}
else
{
temp_pointer->get_Rightslib()=new TreeNode<T>;
temp_pointer->get_Rightslib()->get_val()=temp;
creat_help.push(temp_pointer->get_Rightslib());
temp_pointer=temp_pointer->get_Rightslib();
tag=0;
}
}
else
{
if(tag==0)
{
temp_pointer->get_LeftMostcld()=NULL;
tag=1;
}
else
{
temp_pointer->get_Rightslib()=NULL;
}
if(creat_help.empty())
return;
temp_pointer=creat_help.top();
creat_help.pop();
}
}
}
2019-07-17 22:55:23