牛客-剑指offer系列题解:二叉搜索树与双向链表

记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。
1、问题描述:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
2、数据结构:
二叉搜索树
3、题解:
二叉搜索树的中序遍历是有序的。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Convert(self, pRootOfTree):
        # write code here
        if not pRootOfTree:
            return None
        def find_right(node):
            while node.right:
                node = node.right
            return node
        leftnode = self.Convert(pRootOfTree.left)
        rightnode = self.Convert(pRootOfTree.right)
        retnode = leftnode
        if leftnode:
            leftnode = find_right(leftnode)
        else:
            retnode = pRootOfTree
        pRootOfTree.left = leftnode
        pRootOfTree.right = rightnode
        if leftnode != None:
            leftnode.right = pRootOfTree
        if rightnode:
            rightnode.left = pRootOfTree
        return retnode

或者:
中序遍历,处理根节点是这样的:令根节点的左指针指向上一次的最后一个节点,然后最后一个节点指向左子树,然后把根节点赋值给最后一个节点。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Convert(self, pRootOfTree):
        # write code here
        plastnode = None
        def convertnode(pnode,plastnode):
            if not pnode:
                return
            # pcurrent = pnode
            #遍历左子树
            if pnode.left != None:
                 plastnode =  convertnode(pnode.left,plastnode)
            #处理根节点
            pnode.left = plastnode
            if plastnode != None:
                plastnode.right = pnode
            plastnode = pnode
            #遍历右子树
            if pnode.right:
                plastnode =  convertnode(pnode.right,plastnode)
            return plastnode
        plastnode = convertnode(pRootOfTree,plastnode)
        phead = plastnode
        while phead and phead.left :
            phead = phead.left
        return phead

4、复杂度分析:

方法1:

时间复杂度:O(N)

空间复杂度:O(N)

你可能感兴趣的:(牛客-剑指offer系列题解)