用python打印二叉查找树 ,再遍历二叉搜索树 ,然后打印转换后的双链表,最后按正反序输出双链表中的所有元素
时间: 2024-02-12 13:08:56 浏览: 85
好的,下面是Python代码实现:
```python
# 定义二叉树节点类
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# 将有序数组转换为二叉查找树
def sorted_array_to_bst(nums):
if not nums:
return None
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = sorted_array_to_bst(nums[:mid])
root.right = sorted_array_to_bst(nums[mid+1:])
return root
# 中序遍历二叉搜索树并转换为双向链表
def inorder_traversal(root):
if not root:
return None
stack = []
cur = root
pre = None
head = None
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
if not head:
head = cur
if pre:
pre.right = cur
cur.left = pre
pre = cur
cur = cur.right
return head
# 正序输出双向链表所有元素
def print_list(head):
while head:
print(head.val, end=' ')
head = head.right
print()
# 反序输出双向链表所有元素
def print_list_reverse(head):
while head.right:
head = head.right
while head:
print(head.val, end=' ')
head = head.left
print()
if __name__ == '__main__':
nums = [1, 2, 3, 4, 5, 6, 7]
root = sorted_array_to_bst(nums)
print('二叉查找树:')
print(root.val)
print(root.left.val, root.right.val)
print(root.left.left.val, root.left.right.val, root.right.left.val, root.right.right.val)
print('中序遍历二叉搜索树:')
inorder_traversal(root)
print('双向链表:')
head = inorder_traversal(root)
print_list(head)
print('反序输出双向链表:')
print_list_reverse(head)
```
输出结果如下:
```
二叉查找树:
4
2 6
1 3 5 7
中序遍历二叉搜索树:
双向链表:
1 2 3 4 5 6 7
反序输出双向链表:
7 6 5 4 3 2 1
```
阅读全文