使用链表
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return None
l = []
result = []
l.append(pRootOfTree)
while len(l):
cur = l[-1]
if cur.left:
l.append(cur.left)
elif not cur.left and not cur.right:
result.append(cur)
del l[-1]
while len(l):
cur = l[-1]
result.append(cur)
del l[-1]
if cur.right:
l.append(cur.right)
break
else:
cur = l[-1]
result.append(cur)
del l[-1]
l.append(cur.right)
for i , j in enumerate(result[:-1]):
j.right = result[i+1]
result[i+1].left = j
return result[0]
使用递归
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return
self.result = []
self.midTravel(pRootOfTree)
for i , j in enumerate(self.result[:-1]):
j.right = self.result[i+1]
self.result[i+1].left = j
return self.result[0]
def midTravel(self,tree):
if not tree:
return
self.midTravel(tree.left)
self.result.append(tree)
self.midTravel(tree.right)