-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConvertABinaryTreeToDoublyLinkedList
49 lines (40 loc) · 1.29 KB
/
ConvertABinaryTreeToDoublyLinkedList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*************************************************************
class BinaryTreeNode<T> {
T data;
BinaryTreeNode<T> left;
BinaryTreeNode<T> right;
public BinaryTreeNode(T data) {
this.data = data;
}
}
*************************************************************/
import java.util.*;
public class Solution {
public static BinaryTreeNode<Integer> BTtoDLL(BinaryTreeNode<Integer> root) {
Queue<BinaryTreeNode<Integer>> queue = new LinkedList<>();
getInOrder(root,queue);
return createDL(queue);
}
public static void getInOrder(BinaryTreeNode<Integer> root,Queue<BinaryTreeNode<Integer>> queue){
if(root==null)
return ;
getInOrder(root.left,queue);
queue.offer(root);
getInOrder(root.right,queue);
return;
}
public static BinaryTreeNode<Integer> createDL(Queue<BinaryTreeNode<Integer>> queue){
BinaryTreeNode<Integer> root = queue.peek();
BinaryTreeNode<Integer> prev = null;
while(!queue.isEmpty()){
BinaryTreeNode<Integer> node = queue.poll();
node.left = prev;
if(!queue.isEmpty())
node.right = queue.peek();
else
node.right = null;
prev = node;
}
return root;
}
}