"Sword Finger Offer" Brush Question Series-(64) Binary Search Tree and Doubly Linked List

topic

Enter a binary search tree and convert the binary search tree into a sorted circular doubly linked list. It is required that no new nodes can be created, only the point of the node pointer in the tree can be adjusted.

Ideas

The linked list after conversion is required to be sorted, and according to the characteristics of the binary search tree, using the middle-order traversal, each node of the binary tree can be visited in order from small to large.
In a binary tree, each node has two pointers to child nodes. In the doubly linked list, each point also has two pointers, which point to the previous node and the next node respectively. There are similarities between the two. If the pointer to the left child node in the binary search tree can be adjusted to the pointer to the previous node in the linked list, the pointer to the right child node can be adjusted to the next node in the linked list. Pointer to get the result we want.

In-order traversal requires recursion.

Recursive process:
recursively visit the left subtree of the
current node ; change the direction of the current node;
recursively visit the right subtree of the current node;

The whole process needs three pointers: head, pre, cur
head points to the head of the linked list, used for the final return result,
cur represents the node currently being visited,
pre represents the previous node of the current node

How to change the direction of the current node?
Each time a new node is visited, it is equivalent to adding a new node to the linked list, and its relationship with the previous node points to each other, that is, cur.left = pre, pre.right = cur.

Since the result requires a circular linked list, the head and tail of the linked list need to be directed to each other at the end.

Code

"""
# Definition for a Node.
class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
"""
class Solution:
    def treeToDoublyList(self, root: 'Node') -> 'Node':
        if not root: return 
        self.pre = None
        self.dfs(root)
        self.pre.right = self.head
        self.head.left = self.pre
        return self.head

    def dfs(self,cur):
        if not cur: return 
        self.dfs(cur.left)
        if not self.pre:
            self.head = cur
        else:
            cur.left = self.pre
            self.pre.right = cur
        self.pre = cur
        self.dfs(cur.right)

the complexity

Time complexity O(N): N is the number of nodes in the binary tree, and in-order traversal needs to visit all nodes.
Space complexity O(N): In the worst case, that is, when the tree degenerates to a linked list, the recursion depth reaches N, and the system uses O(N) stack space.

Guess you like

Origin blog.csdn.net/weixin_44776894/article/details/107548170