方法一:递归
算法
标准的中序遍历采用 左 -> 根 -> 右 的顺序,其中 左 和 右 的部分调用递归。
本题的处理在于将前一个结点与当前结点链接,因此,必须跟踪最后一个结点,该结点在新的双向链表中是当前最大的。
另外一个细节:我们也需要保留第一个,也就是最小的结点,以完成闭环。
下面是具体算法:
将 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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。