题目来源:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
思路:
看到这道题觉得有点绕没去做的我真是个大傻逼。。。最后被自己坑了,还不是要回来做这道题。。。自己气自己。。。
讲思路,其实很简单。。。有些题解写的天花乱坠看都看不懂。。。
- 首先,根据二叉搜索树的特点,以及题目要求链表是排序的,那么很明显需要用到中序深度遍历(左-根-右)。
- 初始化双向循环链表的头指针head和尾指针tail
- 定义函数中序遍历函数inorder()
- 遍历左子树,找到最左的叶节点,也就是整个二叉树中的最小值,同时赋值给头尾指针。
- 头尾指针只有这一次初始化赋值,之后就按双向循环链表的特点更改指针,假设当前节点为root:
root.left = tail # 设置左指针,如1 ← 2
tail.right = root # 设置右指针,如1 → 2,双向设置完毕
tail = root # 移动尾指针,到当前节点 - 遍历右子树
- 调用inorder()函数,此时已经构建好了一个基本的双向循环链表,但是尾结点和头结点还没有互相指向,所以再执行一步:
head.left = tail
tail.right = head - 返回头结点head
代码:
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
class Solution(object):
def treeToDoublyList(self, root):
"""
:type root: Node
:rtype: Node
"""
if not root:
return root
self.head = None
self.tail = None
def inorder(root):
if not root:
return
inorder(root.left) # 遍历左子树
if not self.head: # 找到最左节点,初始赋值头尾指针
self.head = root
self.tail = root
else:
root.left = self.tail # 设置左指针
self.tail.right = root # 设置右指针
self.tail = root # 调整tail到当前节点
inorder(root.right)
inorder(root)
self.head.left = self.tail # 连接头尾节点
self.tail.right = self.head
return self.head