【剑指offer】二叉搜索树与双向连接

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36372879/article/details/84258821

题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
普通的二叉树也可以转换成双向链表,只不过不是排序的


思路:

  1. 与中序遍历相同
  2. 采用递归,先链接左指针,再链接右指针

代码1,更改doubleLinkedList,最后返回list的第一个元素:

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    def lastElem(self, list):
        if len(list) == 0:
            return None
        else: return list[len(list) - 1]
    def ConvertCore(self, pRoot, doubleLinkedList):
        if pRoot:
            if pRoot.left:
                self.ConvertCore(pRoot.left, doubleLinkedList)
            pRoot.left = self.lastElem(doubleLinkedList)
            if self.lastElem(doubleLinkedList):
                self.lastElem(doubleLinkedList).right = pRoot
            doubleLinkedList.append(pRoot)
            if pRoot.right:
                self.ConvertCore(pRoot.right, doubleLinkedList)
    def Convert(self, pRootOfTree):
        if pRootOfTree == None:
            return None
        doubleLinkedList = []
        self.ConvertCore(pRootOfTree, doubleLinkedList)
        return doubleLinkedList[0]

代码2,lastListNode指向双向链表中的最后一个节点,因此每次操作最后一个节点。这里要更改值,因此采用list的形式。

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    def ConvertCore(self, pRoot, lastListNode):
        if pRoot:
            if pRoot.left:
                self.ConvertCore(pRoot.left, lastListNode)
            pRoot.left = lastListNode[0]
            if lastListNode[0]:
                lastListNode[0].right = pRoot
            lastListNode[0] = pRoot
            if pRoot.right:
                self.ConvertCore(pRoot.right, lastListNode)
    def Convert(self, pRootOfTree):
        # write code here
        if pRootOfTree == None:
            return None
        lastListNode = [None]
        self.ConvertCore(pRootOfTree, lastListNode)
        while lastListNode[0].left:
            lastListNode[0] = lastListNode[0].left
        return lastListNode[0]

猜你喜欢

转载自blog.csdn.net/weixin_36372879/article/details/84258821