Skip to content

Commit fe0d0c7

Browse files
committed
二叉排序树III
1 parent 5f375f6 commit fe0d0c7

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

第7章/6-4.py

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
"""
2+
6-4 二叉排序树III-Python
3+
已知二叉树T的结点形式为(lling,data,count,rlink),在树中查找值为X的结点,若找到,则记数(count)加1,否则,作为一个新结点插入树中,插入后仍为二叉排序树,写出其非递归算法。
4+
5+
函数接口定义:
6+
在这里描述函数接口。例如:
7+
def search_bst(self, target):
8+
9+
输入样例:
10+
在这里给出一组输入。例如:
11+
5
12+
3
13+
1
14+
#
15+
#
16+
4
17+
#
18+
#
19+
7
20+
6
21+
#
22+
#
23+
9
24+
#
25+
#
26+
7
27+
28+
输出样例:
29+
在这里给出相应的输出。例如:
30+
1.count=0
31+
3.count=0
32+
4.count=0
33+
5.count=0
34+
6.count=0
35+
7.count=1
36+
9.count=0
37+
38+
@Author: FoskyM
39+
@Date: 2023-12-21 21:58
40+
"""
41+
42+
class BinaryTree:
43+
44+
def __init__(self, data=None):
45+
self.data = data # 数据域 data 默认为 None,data 为 None 时表示⼀颗空树
46+
self.lchild = None
47+
self.rchild = None
48+
self.count = 0
49+
50+
def create_bitree(self):
51+
# 按先序次序输入二叉树中结点的值(一个字符),创建二叉链表表示的二叉树
52+
ch = input()
53+
if ch == '#': # 递归结束,建空树
54+
self.data = None
55+
else: # 递归创建二叉树
56+
self.data = ch # 根结点的数据域赋值为ch
57+
self.lchild = BinaryTree() # 为当前结点创建一个空的左子树
58+
self.lchild.create_bitree() # 递归创建左子树
59+
self.rchild = BinaryTree() # 为当前结点创建一个空的右子树
60+
self.rchild.create_bitree() # 递归创建右子树
61+
62+
def in_order_traverse(self):
63+
# 中序遍历二叉树的递归算法
64+
if self.data is not None: # 若二叉树非空
65+
if self.lchild is not None: self.lchild.in_order_traverse() # 中序遍历左子树
66+
print(self.data + '.count=' + str(self.count)) # 访问根结点
67+
if self.rchild is not None: self.rchild.in_order_traverse() # 中序遍历右子树
68+
69+
def search_bst(self, target):
70+
p = self
71+
while p.data is not None:
72+
if target == p.data:
73+
p.count += 1
74+
break
75+
q = p
76+
if target < p.data:
77+
p = p.lchild
78+
else:
79+
p = p.rchild
80+
if p.data is None:
81+
s = BinaryTree(target)
82+
if target < q.data:
83+
q.lchild = s
84+
else:
85+
q.rchild = s
86+
87+
88+
89+
##请在这里填写答案
90+
91+
if __name__ == '__main__':
92+
bt = BinaryTree()
93+
bt.create_bitree()
94+
95+
x = input()
96+
bt.search_bst(x)
97+
98+
bt.in_order_traverse()

0 commit comments

Comments
 (0)