题目
思路
分治,拆分子问题即可。
但是,有一个小坑啊啊啊!
root连接了左右的node之后,左右的node的next和pre也要连接上node啊!!调了半天ε=(´ο`*)))
好困。
代码
"""
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
"""
class Solution:
"""
@param: root: The root of tree
@return: the head of doubly list node
"""
def convert(self, root):
if not root:
return None, None
rootListNode = DoublyListNode(root.val)
leftHead, leftTail = self.convert(root.left)
rightHead, rightTail = self.convert(root.right)
rootListNode.prev = leftTail
rootListNode.next = rightHead
if leftTail:
leftTail.next = rootListNode
if rightHead:
rightHead.prev = rootListNode
if leftHead and rightTail:
return leftHead, rightTail
elif leftHead:
return leftHead, rootListNode
elif rightTail:
return rootListNode, rightTail
else:
return rootListNode, rootListNode
def bstToDoublyList(self, root):
# write your code here
return self.convert(root)[0]