-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeToList.java
More file actions
79 lines (68 loc) · 1.94 KB
/
TreeToList.java
File metadata and controls
79 lines (68 loc) · 1.94 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//Given a Binary Tree(BT), convert it to a Doubly Linked List(DLL) In-place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as Inorder of the given binary tree. The first node of Inorder traversal (left most node in BT) must be head node of the DLL
class Node{
int val;
Node left;
Node right;
Node(int val){
this.val = val;
this.left = null;
this.right = null;
}
}
public class TreeToList{
public static Node tree_to_list(Node root){
Node result = null;
if(root != null && root.left == null && root.right == null)
return root;
if(root != null){
//left and right are heads of left DLL and right DLL
Node left = tree_to_list(root.left); //tree to list for left subtree
Node right = tree_to_list(root.right); //tree to list for right subtree
if(left != null && right != null){
Node temp = left;
while(temp.right != null)
temp = temp.right;
temp.right = root;
root.left = temp;
root.right = right;
right.left = root;
result = left;
return result;
}
else if(left == null && right != null){
root.right = right;
right.left = root;
result = root;
return result;
}
else if(left != null && right == null){
Node temp = left;
while(temp.right != null)
temp = temp.right;
temp.right = root;
root.left = temp;
root.right = null;
result = left;
return result;
}
}
return result;
}
public static void main(String[] args){
//create the binary tree first
Node root = new Node(10);
root.left = new Node(12);
root.left.left = new Node(25);
root.left.right = new Node(30);
root.right = new Node(15);
root.right.left = new Node(36);
Node nroot = tree_to_list(root);
Node temp = nroot;
if(temp == null)
System.out.println("null");
while(temp != null){
System.out.print(temp.val + " ");
temp = temp.right;
}
}
}