Python algorithm Exercise--turning the search tree into a doubly linked list

Source: Internet
Author: User

The topics currently shared in this article are from July, and then the specific algorithms are implemented. The main implementation logic of the search tree-to-bidirectional list is to adjust the left and right subtree of the node in the middle sequence traversal, because the middle sequence traversal is recursive call, so in the adjustment must pay attention to adjust the position, if written wrong, it is likely to cause a dead loop. The main way to avoid this is to adjust the left node when you finish reading Zuozi, and adjust the right node when you have finished traversing the right subtree, see the trans function for the specific code. The time complexity of the algorithm is O (LOGN).

When the input tree is built, it is:

The code is as follows:

#-*-Coding:utf-8-*-"" "Title: Enter a binary search tree (remember the search tree) and convert the two-fork search tree into a sorted doubly linked list. Requirement: You cannot create any new nodes, only the point pointers of the nodes in the tree can be adjusted.    1 2 3 4 5 6 7 Input sequence 4 3 1 2 5 6 7 Use this order to establish a two-fork search tree basic idea: in the way of sequential traversal, each node should be connected to the left of the left dial hand number of the rightmost node, and the right side of the tree should be the leftmost node "" "Class TreeNode: The node definition of the tree, many of which are based on the node's "" "Def __init__ (self):" "Defines a tree node, the initial state left and right nodes are empty" "" self.        Leftnode = None Self.rightnode = None def setData (self, data): "" "Set the number of methods Args:data node value        "" "Self.data = Data def setleftnode (self, Leftnode):" "Sets the method of the left node Args:leftnode the left node "" "Self.leftnode = Leftnode def setrightnode (self, Rightnode):" "Sets the method of the right node args:r Ightnode right Node "" "Self.rightnode = Rightnode def getData (self):" "" Get Node Number return: Return to section        Point number "" "Return Self.data def Getleftnode (self):" "" Get left Node return: Return left node "" " Return Self.leftnode def getrightnode (self): "" "Get Right Node return: Return Right node" "" Return Self.rightnodeclass Buildtree: "" Build binary search in input order        Find the tree, the left side is smaller than the root node, the right side of the larger than the root node "" "Def build (Self, dataList):" "Start to build the tree args:datalist tree node value" ""             #遍历输入数组 for I in range (len (dataList)): Currdata = Datalist[i] #初始化一个节点             Newtreenode = TreeNode () newtreenode.setdata (currdata);                #如果是一个输入, the binary lookup tree is built as the root node of the tree if I==0:self.tree = Newtreenode #否则进行大小的比较 Else:flagnode = Self.tree while Flagnode was not none:if Currdata & Lt;= flagnode.getdata (): #如果当然值小于等于根节点, and the left node is empty, then the left node is assigned if Flagnode.getl                         Eftnode () is None:flagNode.setLeftNode (Newtreenode) break; else: #否则继续找左节Point flagnode = Flagnode.getleftnode () Else: #如果当然值大于根                                                         node, and the right node is empty, the right node assignment if Flagnode.getrightnode () is None:                        Flagnode.setrightnode (Newtreenode) break; else: #否则继续找右节点 Flagnode = Flagnode.getrightnode () def trans (self , Tempnode): "" "recursion for the middle sequence traversal after the left subtree traversal, find Zuozi the rightmost node, as the node Zuozi in the right subtree traversal, find Zuozi the most right node, as the right sub-tree of the node arg S:tempnode Initial tree root node "" "If Tempnode is not None: #递归遍历左子树 Self.trans (tempnode.getleftn Ode ()) #左子树遍历完成, for the left-most-right node find if Tempnode.getleftnode () is not none:tempnode2 = Tempno De.getleftnode () while Tempnode2.getrightnode () was not none:tempnode2 = Tempnode2.getri Ghtnode () Tempnode.setlEftnode (TempNode2) Tempnode2.setrightnode (tempnode) #递归遍历右子树 Self.trans (tempnode.getr Ightnode ()) #右子树遍历完成, the right leftmost node is found if Tempnode.getrightnode () is not none:tempnode2 = Tempnode.getrightnode () while Tempnode2.getleftnode () was not none:tempnode2 = TempNode2 . Getleftnode () Tempnode.setrightnode (TempNode2) Tempnode2.setleftnode (tempnode) def callt    Rans (self): "" "Call Trans with root node" "" Self.trans (Self.tree); def test (self): "" "test data, read from left to right and read from right to left" "" Tempnode = Self.tree while tempnode.ge Tleftnode () is not None: #找到最左节点 Tempnode = Tempnode.getleftnode () #print Tempnode.getdat A () #从左向右读 while Tempnode.getrightnode () are not none:print tempnode.getdata () Tempnod E = Tempnode.getrightnode () print Tempnode.getdata() #从右向左读 while tempnode are not none:print tempnode.getdata () Tempnode = Tempnode.get Leftnode () if __name__ = = "__main__": #初始化数组 dataList = [10,6,4,8,2,5,7,9,20,15,28,14,16,24,29] test = Buildtre E () #构建排序数 test.build (dataList) #递归构建双向链表 Test.calltrans () #测试输出 test.test ()????????????

Output Result:

2 4 5 6 7 8 9 10 14 15 16 20 24 28 29 29 28 24 20 16 15 14 10 9 8 7 5 4 2

Welcome to the subscription number "vernacular algorithm"

Python algorithm Exercise--turning the search tree into a doubly linked list

Related Article

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.