Topic
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.
Solving
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