编程:把二元查找树转成排序的双向链表

二元查找树的特点是,左孩子值 < 节点当前值 < 有孩子值。该转换要求不开辟新的节点,只是实现指针的变换。解决此题有两种思路:
1. 递归:很多有关树的题都可以用递归来解决。首先,要缕清思路。对于当前节点,首先把左子树转换成双向链表,同时返回左子树链表的最大值,也就是最后一个节点;创立最后一个节点和当前节点的双向指针关系;然后把右子树转换成双向链表,返回子链表的最小值,也就是最左边的节点,然后跟当前节点建立双向指针关系。

"""
定义节点结构
class Node(object):
    def __init__(self, left, right, val):
        self.left = left
        self.right = right
        self.val = val
"""
class Solution:
    def convertToBiList(root, flag=False):
        if root == None:
            return None
        leftNode = convertToBiList(root.left, False)
        rightNode = convertToBiList(root.right,True)
        if leftNode is not None:
            leftNode.right = root
        root.left = leftNode
        if rightNode is not None:
            rightNode.left = root
        root.right = rightNode
        if flag:
            while root.left:
                root = root.left
            node = root
        else:
            while root.right:
                root = root.right
            node = root
        return node

2.中序遍历
中序遍历的访问顺序刚好是双向链表的排序

def _convertToBiList(node):
    if node is None:
        return 
    global lastNodeInList
    if node.left is not None:
        _convertToBiList(node.left)
    node.left = lastNodeInList
    if lastNodeInList:
        lastNodeInList.right = node
    lastNodeInList = node
    if node.right is not None:
        _convertToBiList(node.right)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值