NameError: name 'CreateBTree2' is not defined 以下代码:from collections import deque class BTNode: #二叉链中结点类 def init(self,d=None): #构造方法 self.data=d self.lchild=None self.rchild=None class BTree: #二叉树类 def init(self,d=None): #构造方法 self.root=BTNode(d) def DispBTree(self): #返回二叉链的括号表示串 return self._DispBTree1(self.root) def _DispBTree1(self,t): #被DispBTree方法调用 if t==None: return '' else: return '(%s%s%s)' % (t.data,self._DispBTree1(t.lchild),self._DispBTree1(t.rchild)) def FindNode(self,x): #查找值为x的结点算法 return self._FindNode1(self.root,x) def _FindNode1(self,t,x): #被FindNode方法调用 if t==None: return None elif t.data==x: return t else: p=self._FindNode1(t.lchild,x) if p!=None: return p else: return self._FindNode1(t.rchild,x) def Height(self): #求二叉树高度的算法 return self._Height1(self.root) def _Height1(self,t): #被Height方法调用 if t==None: return 0 else: return max(self._Height1(t.lchild),self._Height1(t.rchild))+1 def PreOrder(bt): #先序遍历的递归算法 _PreOrder(bt.root) def _PreOrder(t): #被PreOrder方法调用 if t!=None: print(t.data,end=' ') _PreOrder(t.lchild) _PreOrder(t.rchild) def InOrder(bt): #中序遍历的递归算法 _InOrder(bt.root) def _InOrder(t): #被InOrder方法调用 if t!=None: _InOrder(t.lchild) print(t.data,end=' ') _InOrder(t.rchild) def PostOrder(bt): #后序遍历的递归算法 _PostOrder(bt.root) def _PostOrder(t): #被PostOrder方法调用 if t!=None: _PostOrder(t.lchild) _PostOrder(t.rchild) print(t.data,end=' ') def LevelOrder(bt): #层次遍历的算法 Q=deque() Q.append(bt.root) while len(Q)!=0: t=Q.popleft() print(t.data,end=' ') if t.lchild!=None: Q.append(t.lchild) if t.rchild!=None: Q.append(t.rchild) def CreateBTree2(posts,ins): #由后序序列posts和中序序列ins构造二叉链 n=len(posts) return _CreateBTree2(posts,0,ins,0,n) def _CreateBTree2(posts,i,ins,j,n): #被CreateBTree2方法调用 if n<=0: return None else: r=BTNode(posts[i+n-1]) k=ins.index(posts[i+n-1]) r.lchild=_CreateBTree2(posts,i,ins,j,k-j) r.rchild=_CreateBTree2(posts,i+k-j,ins,k+1,n-(k-j)-1) return r #主程序 ins=[1,2,3,4,5] posts=[5,4,3,2,1] print() print(" 中序:",end=' '); print(ins) print(" 后序:",end=' '); print(posts) print(" 构造二叉树bt") bt=BTree() bt.root=CreateBTree2(posts,len(posts)-1,ins,0,len(ins)) print(" bt:",end=' '); print(bt.DispBTree()) x=值 p=bt.FindNode(x) if p is not None: print(" bt中存在"+x) else: print(" bt中不存在"+x) print(" bt的高度=%d" %(bt.Height())) print(" 先序序列:",end=' '); PreOrder(bt); print() print(" 中序序列:",end=' '); InOrder(bt); print() print(" 后序序列:",end=' '); PostOrder(bt); print() print(" 层次序列:",end=' '); LevelOrder(bt); print()
时间: 2024-02-19 22:58:02 浏览: 75
二叉查找树的编程与实现 C语言.pdf
这个错误是因为在代码中调用了CreateBTree2函数,但是该函数没有被定义。请确认你已经定义或导入了CreateBTree2函数。如果你没有定义这个函数,请添加以下代码到你的程序中:
```
def CreateBTree2(posts,ins):
# 由后序序列posts和中序序列ins构造二叉链
n=len(posts)
return _CreateBTree2(posts,0,ins,0,n)
def _CreateBTree2(posts,i,ins,j,n):
# 被CreateBTree2方法调用
if n<=0:
return None
else:
r=BTNode(posts[i+n-1])
k=ins.index(posts[i+n-1])
r.lchild=_CreateBTree2(posts,i,ins,j,k-j)
r.rchild=_CreateBTree2(posts,i+k-j,ins,k+1,n-(k-j)-1)
return r
```
请确保你已经定义了BTNode和BTree类以及它们的相关方法。
阅读全文