1. Convert a binary search tree into a sorted circular doubly linked list 【Problem Description】 Given a binary search tree, you need to convert it into a circular doubly linked list, the elements in the linked list are sorted. For example, a binary search tree in Fig.1 is converted into a sorted circular doubly linked list in Fig.2. 【Basic Requirements】 The input data is a set of data elements to build a binary search tree, you should design algorithms to realize the conversion process and verify the accuracy of your code on multiple test data. The output includes the following: (1) Print the binary search tree (2) Traverse the binary search tree (3) Print the converted doubly linked list (4) Output all elements of the doubly linked list in positive and reverse order
时间: 2024-01-21 09:02:39 浏览: 127
【Solution】
To convert a binary search tree into a sorted circular doubly linked list, we can use the following steps:
1. Inorder traversal of the binary search tree to get the elements in sorted order.
2. Create a doubly linked list and add the elements from the inorder traversal to it.
3. Make the list circular by connecting the head and tail nodes.
4. Return the head node of the circular doubly linked list.
Here's the Python code for the solution:
```
class Node:
def __init__(self, val):
self.val = val
self.prev = None
self.next = None
def tree_to_doubly_list(root):
if not root:
return None
stack = []
cur = root
head = None
prev = None
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
if not head:
head = cur
if prev:
prev.right = cur
cur.left = prev
prev = cur
cur = cur.right
head.left = prev
prev.right = head
return head
```
To verify the accuracy of the code, we can use the following test cases:
```
# Test case 1
# Input: [4,2,5,1,3]
# Output:
# Binary search tree:
# 4
# / \
# 2 5
# / \
# 1 3
# Doubly linked list: 1 <-> 2 <-> 3 <-> 4 <-> 5
# Doubly linked list in reverse order: 5 <-> 4 <-> 3 <-> 2 <-> 1
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(3)
head = tree_to_doubly_list(root)
print("Binary search tree:")
print_tree(root)
print("Doubly linked list:")
print_list(head)
print("Doubly linked list in reverse order:")
print_list_reverse(head)
# Test case 2
# Input: [2,1,3]
# Output:
# Binary search tree:
# 2
# / \
# 1 3
# Doubly linked list: 1 <-> 2 <-> 3
# Doubly linked list in reverse order: 3 <-> 2 <-> 1
root = Node(2)
root.left = Node(1)
root.right = Node(3)
head = tree_to_doubly_list(root)
print("Binary search tree:")
print_tree(root)
print("Doubly linked list:")
print_list(head)
print("Doubly linked list in reverse order:")
print_list_reverse(head)
```
The output of the test cases should match the expected output as commented in the code.
阅读全文