将一个二叉查找树按照中序遍历转换成双向链表
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
* Definition for Doubly-ListNode.
* public class DoublyListNode {
* int val;
* DoublyListNode next, prev;
* DoublyListNode(int val) {
* this.val = val;
* this.next = this.prev = null;
* }
* }
*/
public class Solution {
/*
* @param root: The root of tree
* @return: the head of doubly list node
*/
public DoublyListNode bstToDoublyList(TreeNode root) {
// write your code here
if(root==null){
return null;
}
DoublyListNode left = bstToDoublyList(root.left);
DoublyListNode result = new DoublyListNode(root.val) ;
DoublyListNode right = bstToDoublyList(root.right);
DoublyListNode temp = left ;
if(left!=null){
while(temp.next!=null){
temp = temp.next;
}
temp.next = result;
result.prev = temp;
}else{
left = result;
}
if(right!=null){
result.next = right;
right.prev = result;
}
return left;
}
}