题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思想:先进行中序遍历,把每个节点保存在list中,然后对list中元素进行连接.
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def midTraver(self, root,listNode):
if root == None:
return
self.midTraver(root.left,listNode)
listNode.append(root)
self.midTraver(root.right,listNode)
def Convert(self, pRootOfTree):
# write code here
if pRootOfTree==None:
return None
listNode=[]
self.midTraver(pRootOfTree,listNode)
pHead=listNode.pop(0)
p=pHead
while len(listNode)>0:
node=listNode.pop(0)
p.right=node
node.left=p
p=p.right
return pHead
if __name__=='__main__':
s=Solution()
root=TreeNode(6)
n1 = TreeNode(4)
n2 = TreeNode(7)
n3 = TreeNode(3)
n4 = TreeNode(5)
root.left=n1
root.right=n2
n1.left=n3
n1.right=n4
nodeList =[]
s.Convert(root)
print(nodeList)