题目
输入一棵二叉树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的节点,只能调整树种节点指针的指向。
例:
输入:
10
/ \
6 14
/ \ / \
4 8 12 16
输出:
4<->6<->8<->10<->12<->14<->16
思路
- 中序遍历二叉搜索树,将节点存入列表,遍历链表调整。
- 时间复杂度:O(n),2次遍历
- 空间复杂度:O(n),列表空间
- 以中序遍历二叉搜索树,将左子树的最大值连接到根节点,将根节点连接到右子树的最小值。
- 时间复杂度:O(n),1次遍历
- 空间复杂度:O(n),最差情况递归深度
代码
思路2:时间复杂度:O(n),空间复杂度:O(n)
def convert_binary_search_tree(root):
"""
:param root: binary search tree root
:return: list node head
"""
def inorder_convert(node, last_node):
"""
:param node: current node
:param last_node: subtree's list head connect to this node
:return: list end
"""
if not node:
return None
# left tree
if node.left:
last_node = inorder_convert(node.left, last_node)
# root
node.left = last_node
if last_node:
last_node.right = node
last_node = node
# right tree
if node.right:
last_node = inorder_convert(node.right, last_node)
return last_node # end of list node
if not root:
return None
head = inorder_convert(root, None)
while head.left:
head = head.left
return head
思考
- 解题思路出来的很快,但是代码实现花了很久。主要原因在于没有想明白递归返回值如何设置。递归每次返回时,代表该子树已经重连成双向链表,而程序下一步应该以中序的顺序,将其余节点连接至其后面。中序的实现就是先递归左子树,在处理根节点(当前节点),在递归右子树。重连发生在根节点处理处。