用python中序遍历二叉搜索树 并输出,然后将其转换为循环的双链表并输出,最后按正反序输出双链表中的所有元素
时间: 2024-02-12 22:09:06 浏览: 70
Python二叉搜索树与双向链表转换算法示例
好的,我来给您讲解一下。
首先,我们需要定义一个二叉树节点类,包括节点值、左右子节点和指向父节点的指针。
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
```
接下来,我们可以先构建一棵二叉搜索树,并对其进行中序遍历,将遍历结果存储在一个列表中。
```python
def inorder_traversal(root, res):
if not root:
return
inorder_traversal(root.left, res)
res.append(root.val)
inorder_traversal(root.right, res)
root = TreeNode(4)
root.left = TreeNode(2)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right = TreeNode(5)
res = []
inorder_traversal(root, res)
print(res) # [1, 2, 3, 4, 5]
```
接下来,我们需要将这棵二叉搜索树转化为循环的双链表。具体做法是,对于每个节点,将其左子节点的最右侧节点指向节点本身,将其右子节点的最左侧节点指向节点本身。
```python
def convert_to_doubly_linked_list(root):
if not root:
return None
convert_to_doubly_linked_list(root.left)
if root.left:
left_rightmost = root.left
while left_rightmost.right:
left_rightmost = left_rightmost.right
left_rightmost.right = root
root.left = left_rightmost
if root.right:
right_leftmost = root.right
while right_leftmost.left:
right_leftmost = right_leftmost.left
right_leftmost.left = root
root.right = right_leftmost
convert_to_doubly_linked_list(root.right)
return root
head = convert_to_doubly_linked_list(root)
while head.left:
head = head.left
while head:
print(head.val)
head = head.right
```
最后,我们需要按照正反序输出双链表中的所有元素。具体做法是,分别从头和尾开始遍历双链表,输出节点值。
```python
def print_doubly_linked_list(head):
while head:
print(head.val)
head = head.right
print_doubly_linked_list(root) # 正序
while root.right:
root = root.right
print_doubly_linked_list(root) # 反序
```
完整代码如下:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
def inorder_traversal(root, res):
if not root:
return
inorder_traversal(root.left, res)
res.append(root.val)
inorder_traversal(root.right, res)
root = TreeNode(4)
root.left = TreeNode(2)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right = TreeNode(5)
res = []
inorder_traversal(root, res)
print(res) # [1, 2, 3, 4, 5]
def convert_to_doubly_linked_list(root):
if not root:
return None
convert_to_doubly_linked_list(root.left)
if root.left:
left_rightmost = root.left
while left_rightmost.right:
left_rightmost = left_rightmost.right
left_rightmost.right = root
root.left = left_rightmost
if root.right:
right_leftmost = root.right
while right_leftmost.left:
right_leftmost = right_leftmost.left
right_leftmost.left = root
root.right = right_leftmost
convert_to_doubly_linked_list(root.right)
return root
head = convert_to_doubly_linked_list(root)
while head.left:
head = head.left
while head:
print(head.val)
head = head.right
def print_doubly_linked_list(head):
while head:
print(head.val)
head = head.right
print_doubly_linked_list(root) # 正序
while root.right:
root = root.right
print_doubly_linked_list(root) # 反序
```
阅读全文