题目描述:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
解题方案:
重写递归函数,其中返回两个参数:头节点和尾节点。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def seq(self, root):
head, tail = root, root
if root.left:
left_head, left_tail = self.seq(root.left)
left_tail.right = head
head.left = left_tail
head = left_head
if root.right:
right_head, right_tail = self.seq(root.right)
tail.right = right_head
right_head.left = tail
tail = right_tail
return head, tail
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return None
head, _ = self.seq(pRootOfTree)
return head