如何根据前序和中序序列建立二叉树

ORAFAN 2002-12-30 05:43:13
已知一棵二叉树的前序序列和中序序列,如何建立这棵二叉树?
...全文
382 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ORAFAN 2002-12-31
  • 打赏
  • 举报
回复
非常感谢!
Riemann 2002-12-31
  • 打赏
  • 举报
回复
#include <iostream >

class CTreeNode
{
public:
CTreeNode(char cVal, CTreeNode * pLeft=0, CTreeNode * pRight=0)
: m_cVal(cVal)
, m_pLeft(pLeft)
, m_pRight(pRight)
{
}
~CTreeNode()
{
if(m_pLeft != 0)
{
delete m_pLeft ;
}
std::cout < < m_cVal ;
if(m_pRight != 0)
{
delete m_pRight ;
}
}
char m_cVal ;
CTreeNode * m_pLeft ;
CTreeNode * m_pRight ;
} ;


CTreeNode * CreateNode(char * sPre, char * sMid, int nSize)
{
if(nSize == 0)
return 0 ;
if(nSize == 1)
return new CTreeNode(*sPre) ;
int nSplitMid ;
for(nSplitMid=0; nSplitMid <nSize; ++nSplitMid)
{
if(sMid[nSplitMid] == sPre[0])
break ;
}
if(nSplitMid == nSize)
return 0 ;
return new CTreeNode(*sPre, CreateNode(sPre+1, sMid, nSplitMid),
CreateNode(sPre+nSplitMid+1, sMid+nSplitMid+1, nSize-nSplitMid-1)) ;
}

int main()
{
CTreeNode * p = CreateNode( "ABCDEFG ", "CBEDAFG ", 7) ;
if(p != 0)
delete p ;
std::cout < < std::endl ;
return 0 ;
}
denghby 2002-12-30
  • 打赏
  • 举报
回复
递归
前序遍历的第一个节点是根节点。在中序遍历的序列中,位于该节点左边的是左子树,位于该节点右边的是右子树。
如果左子树不为空,那么前序遍历的第二个节点就是左子树的根节点,否则就是右子树的根节点。对左右子树再分别重复上述步骤,……,可唯一确定一棵二叉树。
zhoukun666 2002-12-30
  • 打赏
  • 举报
回复
或者C的:
在vc6下:
//未考虑序列的正确性,没有delete掉new的节点
struct TreeNote
{
char m_c;
TreeNote * m_lchild;
TreeNote * m_rchild;
};

void GenTree(CString &st, TreeNote *& tnote)
{
if(st.IsEmpty() == 0)
tnote = new TreeNote;
tnote->m_c = st[0];
st = st.Right(st.GetLength()-1);
if(st[0] != '$')
GenChild(st,tnote->m_lchild);
else
{
tnote->m_lchild = NULL;
st = st.Right(st.GetLength()-1);
}

if(st[0] != '$')
GenChild(st,tnote->m_rchild);
else
{
tnote->m_rchild = NULL;
st = st.Right(st.GetLength()-1);
}
}

zhoukun666 2002-12-30
  • 打赏
  • 举报
回复
我写了一个,大家看看:用类Pascal语言
procedure CreatTree(s:string; var bt:biTree);
new(bt);
i:=1;
if (s[i]='#') //string end with '#'
then [
bt:=nil;
return;
]
bt^.data:=s[i];
Ini_Stack(stack); //initial a stack
push(stack,(bt,0)); //关键,栈元素为(ptr,m)
while not empty(stack) do //其中m=0: ptr没有孩子
[ (pre,m):=pop(stack); m=1: ptr有一个孩子
i:=i+1;
if (s[i]='#') return;
if (s[i]='$')
then [push(stack,(pre,m+1));
continue;
];
if IsChar(s[i])
then [new(p); p^.data:=s[i];
if (m=0)
then [push(stack,(pre,m+1);
pre^.lchild:=p;
];
if (m=1)
then pre^.rchild:=p;
push(stack,(p,0);
];
writeln("input error!");
return;
] //while
endp;

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧