Binary search tree and doubly linked list

Source: Internet
Author: User


Enter a binary search tree and convert the two-fork search tree into a sorted doubly linked list. Requires that no new nodes can be created, only the point pointer of the node in the tree can be adjusted.


According to what can be found is the process of middle order traversal
But we need to change the nexus.
Middle sequence traversal: Zogen right
After adjustment:
Root.left = Listleft
Listleft.right = root

Root.right = Listright
Listright.left = root
The following program in order to return the value is the head node, all first traverse the right subtree, and then adjust the node, and finally traverse the left subtree.

 Public  class solution {TreeNodeList=NULL; PublicTreeNode Convert (TreeNode pnode) {if(Pnode = =NULL)returnPnode; TreeNode pcur = Pnode;if(pcur.right!=NULL) Convert (pcur.right); Pcur.right =List;if(List!=NULL)List. left = Pcur;List= Pcur;if(pcur.left!=NULL) Convert (Pcur.left);return List; }}

The left root right recursive program in discussion

/**public class TreeNode {int val = 0;    TreeNode left = null;    TreeNode right = null;    Public TreeNode (int val) {this.val = val; }}*/ Public  class solution {     PublicTreeNodeConvert(TreeNode Root) {if(root==NULL)return NULL;if(root.left==NULL&&root.right==NULL)returnRoot TreeNode Left=convert (Root.left);//Left node, head node .TreeNode Tmpleft=left;//Find the right node.         while(tmpleft!=NULL&&tmpleft.right!=NULL) {tmpleft=tmpleft.right; }if(left!=NULL){//AdjustmentTmpleft.right=root;        Root.left=tmpleft; } TreeNode Right=convert (root.right);if(right!=NULL) {root.right=right;        Right.left=root; }returnleft!=NULL? left:root; }}

Binary search tree and doubly linked list

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: 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.