剑指offer 面试题36 python版+解析:二叉树与双向链表

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

题目描述

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

思路:采用递归的思想。由于搜索二叉树的左子树的值都小于根节点,右子树的值都大于根节点,因此选择中序遍历,这样可以满足从大到小的顺序遍历每个节点的要求。当遍历到根节点的时候,左子树已经转换成一个排序的链表,链表的最后一个是最大的节点,将其与根节点连接起来。然后去转换右子树,右子树的最小的节点和根节点相连。

# -*- 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 pRootOfTree
        if not pRootOfTree.left and not pRootOfTree.right:
            return pRootOfTree
        #处理左子树
        self.Convert(pRootOfTree.left)
        left  = pRootOfTree.left
        #连接根节点与左子树最大节点
        if left:
            while left.right:
                left = left.right
            pRootOfTree.left, left.right = left, pRootOfTree
        #处理右子树
        self.Convert(pRootOfTree.right)
        right = pRootOfTree.right
        #连接根节点与右子树最小节点
        if right:
            while right.left:
                right = right.left
            pRootOfTree.right, right.left = right, pRootOfTree
        #全部连接完以后需要找到头节点
        while pRootOfTree.left:
            pRootOfTree = pRootOfTree.left
        return pRootOfTree

猜你喜欢

转载自blog.csdn.net/mabozi08/article/details/88854417