Algorithm 22 to turn the two-dollar lookup tree into a sorted doubly linked list (middle-order traversal)

Source: Internet
Author: User

Topic:
Enter a two-dollar lookup tree to convert the two-dollar lookup tree into a sorted doubly linked list.
Requires that no new nodes be created, only the pointer is adjusted.

10
/ /
6 14
/ / / /
4 8 12 16

Convert to doubly linked list
4=6=8=10=12=14=16.

The essence of this problem is to investigate the use of recursion and the traversal of trees. The result of the ordinal traversal of the two-tuple lookup number is the order of the ordered target nodes.

Simply link the nodes to the end of the list in the order of the middle order traversal.

Code:

 template<typename t> struct TreeNode {T data; treenode* Plchild; treenode* Prchild; }; Requires two output parameters to be initialized to null template<typename t> void convertbstree2list (the root node of the treenode<t>* ptreeroot/* tree */, treenode<t>*& plisthead/* The head pointer of the doubly linked list */, treenode<t>*& plistlast/* the tail pointer of the doubly linked list */) {if (Ptreeroot = = NULL) {return;} The middle sequence traverses the left subtree convertbstree2list (Ptreeroot->plchild, Plisthead, plistlast); Handle the current node, link the node to the tail of the doubly linked list//modify the left pointer of the current node, pointing to the tail of the doubly linked list ptreeroot->plchild = Plistlast; if (plistlast)//not the first node {plistlast->prchild = Ptreeroot;} else//First Node {plisthead = Ptreeroot;} plistlast = Ptreer Oot The middle sequence traverses right subtree convertbstree2list (Ptreeroot->prchild, Plisthead, plistlast); }

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.