二叉排序数转化双向链表

解题思路:中序遍历是有序的。使用了一个指针来保存链表的最后的节点。每次中序遍历到了根节点,就把根节点添加到了中序遍历的链表的末尾。这样遍历结束就能得到了一个中序有序的链表。最后再利用末尾指针逆序找到头结点即可。

代码如下:

class Node:
    def __init__(self, x,y=None,z=None):
        self.value=x
        self.left=y
        self.right=z


class Solution:
    def convert(self, root):
        self.DoubleListNode=None
        self.convertnode(root)
        phead=self.DoubleListNode
        while phead and phead.left:
            phead=phead.left
        return phead


    def convertnode(self, root):
        if root ==None:
            return
        pcur=root
        if pcur.left:
            self.convertnode(pcur.left)
        pcur.left=self.DoubleListNode
        if self.DoubleListNode:
            self.DoubleListNode.right=pcur
        self.DoubleListNode=pcur
        if pcur.right:
            self.convertnode(pcur.right)

a4=Node(4)
a8=Node(8)
a12=Node(12)
a16=Node(16)
a6=Node(6,a4,a8)
a14=Node(14,a12,a16)
a10=Node(10,a6,a14)
solution=Solution()
head=solution.convert(a10)
while head:
    print(head.value)
    head=head.right
原文地址:https://www.cnblogs.com/tsdblogs/p/9855262.html