题目:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
解答:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import Queue
class Solution:
def Convert(self, pRootOfTree):
# write code here
self.q = Queue.Queue()
if not pRootOfTree: return
self.iterate(pRootOfTree)
pHead = None
pTail = None
while(not self.q.empty()):
node = self.q.get()
if pTail == None:
pTail = node
if pHead == None:
pHead = node
continue
node.left = pHead
pHead.right = node
pHead = node
return pTail
def iterate(self, root):
if not root: return
self.iterate(root.left)
self.q.put(root)
self.iterate(root.right)