二元查找树的特点是,左孩子值 < 节点当前值 < 有孩子值。该转换要求不开辟新的节点,只是实现指针的变换。解决此题有两种思路:
1. 递归:很多有关树的题都可以用递归来解决。首先,要缕清思路。对于当前节点,首先把左子树转换成双向链表,同时返回左子树链表的最大值,也就是最后一个节点;创立最后一个节点和当前节点的双向指针关系;然后把右子树转换成双向链表,返回子链表的最小值,也就是最左边的节点,然后跟当前节点建立双向指针关系。
"""
定义节点结构
class Node(object):
def __init__(self, left, right, val):
self.left = left
self.right = right
self.val = val
"""
class Solution:
def convertToBiList(root, flag=False):
if root == None:
return None
leftNode = convertToBiList(root.left, False)
rightNode = convertToBiList(root.right,True)
if leftNode is not None:
leftNode.right = root
root.left = leftNode
if rightNode is not None:
rightNode.left = root
root.right = rightNode
if flag:
while root.left:
root = root.left
node = root
else:
while root.right:
root = root.right
node = root
return node
2.中序遍历
中序遍历的访问顺序刚好是双向链表的排序
def _convertToBiList(node):
if node is None:
return
global lastNodeInList
if node.left is not None:
_convertToBiList(node.left)
node.left = lastNodeInList
if lastNodeInList:
lastNodeInList.right = node
lastNodeInList = node
if node.right is not None:
_convertToBiList(node.right)