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
我的思路还是追求逻辑最简单,思路最Straightforward但最不容易出错的“傻壮”方法。先求出inorder traversal的ArrayList, 然后将ArrayList转换成Doubly Linked List.
/**
* 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
// brute force: first do inOrder traversal, then convert the
// list to a doubly linked list
List<Integer> inOrder = new ArrayList<>();
if (root == null){
return null;
}
TreeNode curt = root;
Stack<TreeNode> stack = new Stack<>();
while (curt != null){
stack.push(curt);
curt = curt.left;
}
while (!stack.isEmpty()){
TreeNode node = stack.pop();
inOrder.add(node.val);
curt = node.right;
while (curt != null){
stack.push(curt);
curt = curt.left;
}
}
DoublyListNode res = new DoublyListNode(0);
res.prev = null;
DoublyListNode dummy = res;
if (inOrder.size() == 1){
return new DoublyListNode(inOrder.get(0));
}
for (int i = 0; i < inOrder.size() - 1; i++){
DoublyListNode curtNode = new DoublyListNode(inOrder.get(i));
DoublyListNode nextNode = new DoublyListNode(inOrder.get(i + 1));
curtNode.next = nextNode;
nextNode.prev = curtNode;
res.next = curtNode;
curtNode.prev = res;
res = res.next;
}
return dummy.next;
}
}