title : A binary lookup tree is converted into a doubly linked list according to the middle order traversal.
Given a binary lookup tree:
4 / 2 5 / 1 3
Return 1<->2<->3<->4<->5
.
idea : If for the current node, the right subtree into a doubly linked list, and then the left sub-tree into a doubly linked list, the conversion when we have marked the list of the head node and tail node, then only the current node and the left sub-tree to connect the tail, and the right subtree of the head connected.
Java code: This is a reference to the nine chapters inside the problem-solving method. However, the conversion of the left and right sub-tree into a binary tree is not very understanding, still need to continue to analyze.
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *} * Definition for D Oubly-listnode. * public class Doublylistnode {* int val; * Doublylistnode Next, prev; * Doublylistnode (int val) {* This.val = val; * This.next = This.prev = null; * } * } */ classResulttype {Doublylistnode First, last; PublicResulttype (Doublylistnode First, Doublylistnode last) { This. First =First ; This. Last =Last ; }} Public classSolution {/** * @paramroot:the root of tree *@return: The head of doubly list node*/ PublicDoublylistnode bsttodoublylist (TreeNode root) {if(Root = =NULL) { return NULL; } resulttype result=helper (root); returnResult.first; } PublicResulttype Helper (TreeNode root) {if(Root = =NULL) { return NULL; } Resulttype Left=Helper (Root.left); Resulttype Right=Helper (root.right); Doublylistnode node=NewDoublylistnode (Root.val); Resulttype result=NewResulttype (NULL,NULL); if(left = =NULL) {Result.first=node; } Else{Result.first=left.first;//????? Left.last.next=node; Node.prev=Left.last; } if(right = =NULL) {Result.last=node; } Else{result.last=right.last;//????? Right.first.prev=node; Node.next=Right.first; } returnresult; }}
Novice Learning Algorithm----binary tree (a binary lookup tree is transformed into a doubly linked list by the middle-order traversal)