zoukankan      html  css  js  c++  java
  • 二叉排序数转化双向链表

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

    代码如下:

    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
  • 相关阅读:
    kubeadm升级证书-集群已GG
    匿名内部类
    JAVA中Integer的==和equals注意
    编写高效优雅安全Java程序的常见原则
    图解排序算法(二)之希尔排序
    String常见问题
    ActiveMQ 2
    消息中间件概述和AaciveMQ 1
    类加载器-5
    使用MyBatis编写Dao的两种语法
  • 原文地址:https://www.cnblogs.com/tsdblogs/p/9855262.html
Copyright © 2011-2022 走看看