leetcode题解 426. Convert Binary Search Tree to Sorted Doubly Linked List

方法一:递归
算法

标准的中序遍历采用 左 -> 根 -> 右 的顺序,其中 左 和 右 的部分调用递归。

本题的处理在于将前一个结点与当前结点链接,因此,必须跟踪最后一个结点,该结点在新的双向链表中是当前最大的。

另外一个细节:我们也需要保留第一个,也就是最小的结点,以完成闭环。

下面是具体算法:

将 first 和 last 结点 初始化为 null。

调用标准中序遍历 helper(root) :

若结点不为 null :

调用左子树递归 helper(node.left)。

若 last 结点不为空,将 last 与当前的 node 链接。

否则初始化 first 结点。

将当前结点标记为最后 : last = node.

调用右子树递归 helper(node.right)。

将最前与最后的结点链接完成闭环,返回 first 。

实现

class Solution:
    def treeToDoublyList(self, root: 'Node') -> 'Node':
        def helper(node):
            """
            Performs standard inorder traversal:
            left -> node -> right
            and links all nodes into DLL
            """
            nonlocal last, first
            if node:
                # left
                helper(node.left)
                # node 
                if last:
                    # link the previous node (last)
                    # with the current one (node)
                    last.right = node
                    node.left = last
                else:
                    # keep the smallest node
                    # to close DLL later on
                    first = node        
                last = node
                # right
                helper(node.right)
        
        if not root:
            return None
        
        # the smallest (first) and the largest (last) nodes
        first, last = None, None
        helper(root)
        # close DLL
        last.right = first
        first.left = last
        return first

复杂度分析

时间复杂度:{O}(N)O(N),每个结点被处理一次。
空间复杂度:{O}(N)O(N)。需要树高度大小的递归栈,最好情况(平衡树)为 {O}(\log N)O(logN),最坏情况下(完全不平衡)为 O(N)O(N)。

作者:LeetCode
链接:https://leetcode-cn.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/solution/jiang-er-cha-sou-suo-shu-zhuan-hua-wei-pai-xu-de-s/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值