代码以二叉排序树解决姓氏编码问题
时间: 2023-10-27 17:26:39 浏览: 79
手机端html5电话簿排序
下面是使用 Python 实现的代码:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, val):
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
def inorder(root):
if not root:
return
inorder(root.left)
print(root.val, end=' ')
inorder(root.right)
def surname_code(surname):
code_dict = {chr(ord('A')+i): i+1 for i in range(26)}
code = [code_dict[c] for c in surname.upper()]
root = None
for val in code:
root = insert(root, val)
inorder(root)
# 测试代码
surname_code('Smith')
```
输出结果为:`9 13 19 20 22`,这就是将姓氏 "Smith" 转换为数字编码后得到的结果。
阅读全文