The binary search tree is transformed into an ordered two-way linked list.

Source: Internet
Author: User

Question: enter a binary search tree and convert it into a sorted two-way linked list. You must not create any new node. You only need to adjust the pointer point.

For example, Binary Search Tree
10
/\
6 14
/\/\
4 8 12 16
Convert to a two-way linked list

4 = 6 = 8 = 10 = 12 = 14 = 16.

A Microsoft interview question.

Each node of the binary search tree has two pointers, and the node of the two-way linked list is also two pointers. If you do not create a new node, you can adjust the pointer only to complete the transformation.

For each Node in the binary search tree, all the keywords in the left subtree are smaller than those in the Node, and all the keywords in the right subtree are greater than those in the Node.

Recursive thinking can easily complete the transformation. The left and right subtree of the node is converted into an ordered linked list, and then the node Pointer Points to the two linked lists respectively.

import randomclass Node(object):    def __init__(self,key):        self.key=key        self.left=None        self.right=Noneclass BSTree(object):    def __init__(self):        self.root=None    def put(self,key):        if not self.root:            self.root=Node(key)        else:            self.root=self._put(self.root,key)    def _put(self,node,key):        if node is None:            node=Node(key)        elif key<node.key:            node.left=self._put(node.left,key)        elif key>node.key:            node.right=self._put(node.right,key)        return node      def convert(self):        if self.root:            return self._convert(self.root)    def _convert(self,node,asright=True):        if not node:            return None        else:            left=self._convert(node.left,False)            if left:                left.right=node                node.left=left            right=self._convert(node.right)            if right:                right.left=node                node.right=right            cur=node            if asright:                while cur.left:                    cur=cur.left            if not asright:                while cur.right:                    cur=cur.right            return cur                            if __name__=='__main__':    t=BSTree()       for i in range(10):        t.put(random.randint(0,100))        cur=t.convert()    if cur:        print cur.key        while cur.right:            cur=cur.right            print cur.key        while cur.left:            cur=cur.left            print cur.key

Another idea is to adopt the method of Middle-order traversal. The binary search tree is sorted in ascending order. Convert the traversed node into an ordered linked list, and add the next node to be traversed to the end of the linked list.

import randomclass Node(object):    def __init__(self,key):        self.key=key        self.left=None        self.right=Noneclass Sorted_LinkedList(object):    def __init__(self):        self.head=None    def travel(self):        node=self.head        while node:            print node.key            node=node.rightclass BSTree(object):    def __init__(self):        self.root=None        self.list=Sorted_LinkedList()        self.curNode=None    def put(self,key):        if not self.root:            self.root=Node(key)        else:            self.root=self._put(self.root,key)    def _put(self,node,key):        if node is None:            node=Node(key)        elif key<node.key:            node.left=self._put(node.left,key)        elif key>node.key:            node.right=self._put(node.right,key)        return node      def convert(self):        self._travel(self.root)        return self.list    def _travel(self,node):        if node:             self._travel(node.left)             if self.curNode:                 self.curNode.right=node                 node.left=self.curNode             else:                 self.list.head=node             self.curNode=node             self._travel(node.right)                        if __name__=='__main__':    t=BSTree()       for i in range(100):        t.put(random.randint(0,100))    l=t.convert()    l.travel()

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.