b_nk_二叉搜索树转双向链表(记录当前结点的前驱结点+中序遍历)

NK. BST转双向链表

将该二叉搜索树转换成一个排序的双向链表,只能调整树中结点指针的指向。

思路:中序遍历

class Solution:
    head,forw=None,None
    def Convert(self , root: TreeNode):
        def dfs(root):
            if not root: return
            dfs(root.left)
            if not self.head: #左子树遍历完毕,此时的结点就是链表的头结点(因为左子树的尽头的数值是最小的)
                self.head=root
                self.cur=root
            else:
                self.cur.right=root
                root.left=self.cur
                self.cur=root
            dfs(root.right)
        dfs(root)
        return self.head

LC. BST转双向循环链表

额外要求:树中节点的左指针需要指向前驱,树中节点的右指针需要指向后继

疑惑:上面的代码在这题通不过,原来这题是转成双向循环链表,加上循环即可

class Solution:
    head,forw=None,None
    def treeToDoublyList(self , root):
        def dfs(root):
            if not root: return
            dfs(root.left)
            if not self.head:
                self.head=self.forw=root
            else:
                self.forw.right=root
                root.left=self.forw
                self.forw=root
            dfs(root.right)
        if not root: return None
        dfs(root)
        self.forw.right, self.head.left=self.head, self.forw
        return self.head
原文地址:https://www.cnblogs.com/wdt1/p/14072814.html