26-Binary Search Tree and Bidirectional Link List

layout: post
title: 26-Binary Search Tree and Bidirectional Link List
category: sword finger offer
tags:
description:

Title Description

Enter a binary search tree and convert the binary search tree into a sorted bidirectional list. Requirements can not create any new nodes, can only adjust the pointer of the node in the tree.

The following code constructs a binary search tree for testing purposes.

class TreeNode:
   def __init__(self, x):
       self.val = x
       self.left = None
       self.right = None

L = {'A': TreeNode(3), 
    'B': TreeNode(2), 
    'C': TreeNode(6), 
    'D': TreeNode(1), 
    'E': TreeNode(4), 
    'F': TreeNode(8), 
    'G': TreeNode(5), 
    'H': TreeNode(7), 
    'I': TreeNode(9)}

L['F'].left, L['F'].right = L['H'], L['I']
L['E'].right = L['G']
L['C'].left, L['C'].right = L['E'], L['F']
L['A'].left, L['A'].right = L['B'], L['C']
L['B'].left = L['D']
root = L['A']

Recursion.

  • The function recur(root) can program a sorted bi-directional list of trees whose roots are roots, and the root is unchanged.
  • According to the characteristics of bi-directional linked list, the end nodes of the bi-directional linked list can be easily obtained.
class Solution:
    # Just traverse in middle order.
    def Convert(self, root):
        def recur(root):
            if root.left:
                recur(root.left)
                lr = root.left
                while lr.right:
                    lr = lr.right
                root.left, lr.right = lr, root
            if root.right:
                recur(root.right)
                rl = root.right
                while rl.left:
                    rl = rl.left
                root.right, rl.left = rl,root
        if root is None:
            return root
        else:
            recur(root)
            while root.left:
                root = root.left
            return root

In order to traverse, the nodes are stored in a list, and then the two-way connection between adjacent nodes is constructed.

class Solution:
    # Just traverse in middle order.
    def Convert(self, pRootOfTree):
        # write code here
        # write code here
        logs = set()
        mystack = []
        mylist = []
        node = pRootOfTree
        while node is not None:
            if id(node) not in logs:
                logs.add(id(node))
                mystack.append(node)
                if node.left:
                    node = node.left
                else:
                    node = mystack.pop(-1)
            else:
                mylist.append(node)
                if node.right:
                    node = node.right
                else:
                    # If the list does not contain elements, pop should not be used or errors will occur
                    if len(mystack) > 0:
                        node = mystack.pop(-1)
                    else:
                        node = None
        if len(mylist) == 0:
            return None
        elif len(mylist) == 1:
            mylist[0].left, mylist[0].right = None, None
            return mylist[0]
        else:
            mylist[0].left = None
            mylist[0].right = mylist[1]
            mylist[-1].right = None
            mylist[-1].left = mylist[-2]
            for i in range(1, len(mylist)-1):
                mylist[i].left = mylist[i-1]
                mylist[i].right = mylist[i+1]
            return mylist[0]

Posted by simshaun on Thu, 03 Oct 2019 14:17:47 -0700