原来题意的双向链表是left和right。小数指向大数是right,大数指向小数是left
看了一下非递归算法,很妙,刚好是中序遍历的非递归
运行时间:26ms
占用内存:5732k
需要注意第一次的时候,只是把中序遍历的第一个结点找到而已
# -*- 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
current = pRootOfTree
nodelist = []
firstnode = True
while (current or nodelist):
while (current):
nodelist.append(current)
current = current.left
current = nodelist.pop()
if (firstnode):
root = current
pre = root
firstnode = False
else:
pre.right = current
current.left = pre
pre = current
current = current.right
return root
——————————————————————————————————————
插播一条递归与非递归的中序遍历
#非递归
def MidSearch(self, pRootOfTree):
# write code here
if not pRootOfTree:
return None
current = pRootOfTree
nodelist = []
# firstnode = True
result = []
while (current or nodelist):
while (current):
nodelist.append(current)
current = current.left
current = nodelist.pop()
result.append(current.val)
current = current.right
return result
#递归
def MidSearch(self, pRootOfTree):
# write code here
res = []
if not pRootOfTree:
return None
if (pRootOfTree.left):
res += self.MidSearch(pRootOfTree.left)
res += [pRootOfTree.val]
if (pRootOfTree.right):
res += self.MidSearch(pRootOfTree.right)
return res
——————————————————————————————————————
递归算法
运行时间:26ms
占用内存:5724k
考虑左右子树分开而且连接的过程
# -*- 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
firstNode = pRootOfTree
if (not pRootOfTree.left and not pRootOfTree.right):
firstNode = pRootOfTree
return pRootOfTree
l = self.Convert(pRootOfTree.left)
if (l):
firstNode = l
while (l.right):
l = l.right
l.right = pRootOfTree
pRootOfTree.left = l
r = self.Convert(pRootOfTree.right)
if (r):
pRootOfTree.right = r
r.left = pRootOfTree
return firstNode