用python将二叉搜索树转换为双向循环链表,防止循环输出,再分别按正序和反序输出链表元素
时间: 2024-02-12 18:09:45 浏览: 73
Python二叉搜索树与双向链表转换实现方法
好的,我来回答你的问题。
下面是将二叉搜索树转换为双向循环链表的Python代码:
```python
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
def treeToDoublyList(root: Node) -> Node:
if not root:
return None
def dfs(node):
if not node:
return
dfs(node.left)
if dfs.prev:
dfs.prev.right = node
node.left = dfs.prev
else:
dfs.head = node
dfs.prev = node
dfs(node.right)
dfs.prev = None
dfs.head = None
dfs(root)
dfs.head.left = dfs.prev
dfs.prev.right = dfs.head
return dfs.head
```
接下来,我们可以分别按正序和反序输出链表元素,如下:
```python
def printList(head: Node):
if not head:
return
curr = head
while curr:
print(curr.val, end=' ')
curr = curr.right
if curr == head:
break
def printListReverse(head: Node):
if not head:
return
curr = head.left
while curr:
print(curr.val, end=' ')
curr = curr.left
if curr == head.left:
break
```
完整的代码如下:
```python
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
def treeToDoublyList(root: Node) -> Node:
if not root:
return None
def dfs(node):
if not node:
return
dfs(node.left)
if dfs.prev:
dfs.prev.right = node
node.left = dfs.prev
else:
dfs.head = node
dfs.prev = node
dfs(node.right)
dfs.prev = None
dfs.head = None
dfs(root)
dfs.head.left = dfs.prev
dfs.prev.right = dfs.head
return dfs.head
def printList(head: Node):
if not head:
return
curr = head
while curr:
print(curr.val, end=' ')
curr = curr.right
if curr == head:
break
def printListReverse(head: Node):
if not head:
return
curr = head.left
while curr:
print(curr.val, end=' ')
curr = curr.left
if curr == head.left:
break
# 测试代码
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(3)
head = treeToDoublyList(root)
printList(head) # 1 2 3 4 5
print()
printListReverse(head) # 5 4 3 2 1
print()
```
希望能够帮助到你!
阅读全文