378. 将二叉查找树转换成双链表
将一个二叉查找树按照中序遍历转换成双向链表。
样例
给定一个二叉查找树:
4
/ \
2 5
/ \
1 3
返回 1<->2<->3<->4<->5
。
实现思路:
两个方法,一个是利用数组保存二叉树中序遍历的结果,然后转换成双向链表。
第二个方法:因为双向链表的prev正好对应树的left,next对应right。所以在中序遍历的过程中直接建立链表。
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
Definition of Doubly-ListNode
class DoublyListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = self.prev = next
"""
#method 1 利用数组存储树,然后转成链表。T(n),S(n)
class Solution:
"""
@param: root: The root of tree
@return: the head of doubly list node
"""
def bstToDoublyList(self, root):
# write your code here
if root is None:
return None
self.result = []
self.dfs(root)
dummy = DoublyListNode(0)
pre = dummy
for res in self.result:
tmp = DoublyListNode(res)
tmp.prev = pre
pre.next = tmp
pre = tmp
dummy.next.prev = None
return dummy.next
def dfs(self, root):
if root is None:
return
self.dfs(root.left)
self.result.append(root.val)
self.dfs(root.right)
#mothed 2 在遍历树的同时,建立链表,T(n),S(h),h是树的高度
class Solution:
"""
@param: root: The root of tree
@return: the head of doubly list node
"""
def __init__(self):
self.listHead = None
self.listTail = None
def bstToDoublyList(self, root):
# write your code here
if root is None:
return None
self.bstToDoublyList(root.left)
if self.listHead == None:
self.listHead = DoublyListNode(root.val)
self.listTail = self.listHead
else:
proot = DoublyListNode(root.val)
self.listTail.next = proot
proot.prev = self.listTail
self.listTail = proot
self.bstToDoublyList(root.right)
return self.listHead