输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
因为二叉搜索树每个节点都有两个指针,分别是指向其左子节点和右子节点,所以将该节点的左子节点变成双向链表中的左节点,将该节点的右子节点变成双向链表中的右节点。采用中序列遍历的方法遍历数组,然后利用递归将左边的最后一个节点和根节点相连,将右边的第一个节点和根节点相连。
python代码:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Convert(self, pRootOfTree):
if not pRootOfTree:
return None
if not pRootOfTree.left and not pRootOfTree.right:
return pRootOfTree
# 将左子树构建成双链表,返回链表头
left = self.Convert(pRootOfTree.left)
p = left
# 定位至左子树的最右的一个结点
while left and p.right:
p = p.right
# 如果左子树不为空,将当前root加到左子树链表
if left:
p.right = pRootOfTree
pRootOfTree.left = p
# 将右子树构造成双链表