问题
Convert a binary search tree to doubly linked list with in-order traversal.
Have you met this question in a real interview? Yes
Example
Given a binary search tree:
return 1<->2<->3<->4<->5
分析
使用递归,注意是遍历的次序。自身的节点是new出来的,只有一个所以比较简单。左边和右边的都可能是一个链表,不是只有一个节点。所以在node指向右边的时候是没有问题的,在指向左边的时候需要把左边的链表遍历到尾节点。
代码
* 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) {
if(root==null){
return null;
}
DoublyListNode left=bstToDoublyList(root.left);
DoublyListNode node=new DoublyListNode(root.val);
DoublyListNode right=bstToDoublyList(root.right);
node.next=right;
if(right!=null){
right.prev=node;
}
if(left!=null){
DoublyListNode temp=left;
while(true){
if(temp.next==null){
temp.next=node;
node.prev=temp;
return left;
}
temp=temp.next;
}
}
return node;
}
}