Convert a binary search tree to doubly linked list with in-order traversal.
Example
Given a binary search tree:
4
/
2 5
/
1 3
return 1<->2<->3<->4<->5
中序遍历 穿针引线
/** * 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 List<DoublyListNode> helper(List<DoublyListNode> hT, TreeNode root) { if (root.left != null) { helper(hT, root.left); } DoublyListNode newNode = new DoublyListNode(root.val); newNode.prev = hT.get(1); hT.get(1).next = newNode; hT.remove(1); hT.add(newNode); if (root.right != null) { helper(hT, root.right); } return hT; } public DoublyListNode bstToDoublyList(TreeNode root) { // Write your code here if (root == null) { return null; } DoublyListNode head = new DoublyListNode(-1); DoublyListNode tail = head; List<DoublyListNode> hT = new ArrayList<DoublyListNode>(); hT.add(head); hT.add(tail); helper(hT, root); hT.get(0).next.prev = null; return hT.get(0).next; } }