题解 | #二叉搜索树与双向链表#
二叉搜索树与双向链表
http://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5
该题看起来就与二叉树的中序遍历有相似之处,所以先写一个中序遍历,改一改就是答案了,如下所示
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# @param pRootOfTree TreeNode类
# @return TreeNode类
#
class Solution:
def Convert(self , pRootOfTree ):
if not pRootOfTree:
return pRootOfTree
stack = []
node = pRootOfTree
result=None
pre=None
now=None
while node or len(stack)>0:
while node:
stack.append(node)
node = node.left
if len(stack)>0:
now =stack.pop()
if not pre:
result =now
if pre:
pre.right=now
now.left=pre
pre = now
node = now.right
return result