To prove safety offer binary search tree python with a doubly linked list

Title Description

Enter a binary search tree, the binary search tree converted into a doubly linked list sorted. Requirements can not create any new node, point to only adjust the tree node pointer.

Thinking

Binary search tree, naturally thought preorder. Preorder out result is sorted. Because you can not create a new node, so we define two pointers, a pointer to the head of the list, a pointer to the current node traversal, traverse to the next node when fit, and create a two-way connection pointer, then this node change The current traversing node.

Code

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def __init__(self):
        self.listHead = None
        self.listTail = None
    def Convert(self, pRootOfTree):
        if not pRootOfTree:
            return 
        self.Convert(pRootOfTree.left)
        if not self.listHead: #遍历的第一个结点
            self.listHead = pRootOfTree
            self.listTail = pRootOfTree
        else:
            self.listTail.right = pRootOfTree
            pRootOfTree.left = self.listTail
            self.listTail = pRootOfTree
        self.Convert(pRootOfTree.right)
        return self.listHead
        

 

Guess you like

Origin www.cnblogs.com/wangzhihang/p/11844869.html