class BSTreeNode: def init(self,data,lchild,rchild): self.data=data self.lchild=lchild self.rchild=rchild def InsertBST(root,data): if root==None: p=BSTreeNode(data,None,None) return p elif data<root.data : root.lchild=InsertBST(root.lchild,data) else: root.rchild=InsertBST(root.rchild,data) return root root=None valstr=list(map(int,input().split())) for i in range(0,len(valstr)): root=InsertBST(root,valstr[i]) 在以上程序中添加一个递减的排序的函数,使Input sample 10 5 3 4 15 20 12 output sample 20 15 12 10 5 4 3 Input sample 10 output sample 10 Input sample 20 10 output sample 20 10 Input sample 10 20 output sample 20 10
时间: 2023-12-22 07:05:54 浏览: 107
可以在已有的 `BSTreeNode` 类中添加一个递减排序的函数 `InOrderDescend(root)`,具体实现如下:
```python
class BSTreeNode:
def __init__(self, data, lchild, rchild):
self.data = data
self.lchild = lchild
self.rchild = rchild
def InsertBST(root, data):
if root == None:
p = BSTreeNode(data, None, None)
return p
elif data < root.data:
root.lchild = InsertBST(root.lchild, data)
else:
root.rchild = InsertBST(root.rchild, data)
return root
def InOrderDescend(root):
if root != None:
InOrderDescend(root.rchild)
print(root.data, end=' ')
InOrderDescend(root.lchild)
```
然后在 `main` 函数中,先按照原来的代码构建出二叉搜索树,再调用 `InOrderDescend` 函数输出递减序列即可。完整代码如下:
```python
class BSTreeNode:
def __init__(self, data, lchild, rchild):
self.data = data
self.lchild = lchild
self.rchild = rchild
def InsertBST(root, data):
if root == None:
p = BSTreeNode(data, None, None)
return p
elif data < root.data:
root.lchild = InsertBST(root.lchild, data)
else:
root.rchild = InsertBST(root.rchild, data)
return root
def InOrderDescend(root):
if root != None:
InOrderDescend(root.rchild)
print(root.data, end=' ')
InOrderDescend(root.lchild)
root = None
valstr = list(map(int, input().split()))
for i in range(0, len(valstr)):
root = BSTreeNode.InsertBST(root, valstr[i])
BSTreeNode.InOrderDescend(root)
```
阅读全文