题目描述
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/
思路题解
取头尾拼接的dfs
自己做的
首先后续遍历,得到左右子树的链表的头尾节点,然后在把中间节点和他们拼接起来,最后返回新的头尾节点。
"""
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
def genList(parent,root):
if not root:return parent,parent
if not root.left and not root.right:
root.right,root.left=parent,root
return root,root
if not root.left:
rl,rr=genList(root,root.right)
root.left=rr
root.right=rl
rl.left=root
return root,rr
if not root.right:
ll,lr=genList(root,root.left)
root.right=parent
root.left=lr
lr.right=root
return ll,root
ll,lr=genList(root,root.left)
rl,rr=genList(root,root.right)
root.left,root.right=lr,rl
lr.right,rl.left=root,root
rr.right=parent
return ll,rr
if not root:return None
ll,lr=genList(root,root.left)
rl,rr=genList(root,root.right)
if rl==root:
rl=ll
if lr==root:
lr=rr
root.left,root.right=lr,rl
lr.right,rl.left=root,root
ll.left,rr.right=rr,ll
# p=ll
# m={}
# while p and p.val not in m:
# print(p.left.val,p.val,p.right.val)
# m[p.val]=1
# p=p.right
return ll
标记遍历的dfs
大佬的做法,妙用self存储前一个节点pre和当前节点cur,其实速度差不多,但是思路很清晰,也很简洁。
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/solution/mian-shi-ti-36-er-cha-sou-suo-shu-yu-shuang-xian-5/
"""
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
class Solution:
def treeToDoublyList(self, root: 'Node') -> 'Node':
def dfs(cur):
if not cur:return
dfs(cur.left)
if not self.pre:
self.head=cur
else:
self.pre.right,cur.left=cur,self.pre
self.pre=cur
dfs(cur.right)
if not root: return
self.pre=None
dfs(root)
self.head.left, self.pre.right = self.pre, self.head
return self.head