-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBinaryTreeToDLL.java
47 lines (40 loc) · 992 Bytes
/
BinaryTreeToDLL.java
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
/*https://practice.geeksforgeeks.org/problems/binary-tree-to-dll/1*/
//inorder traversal approach
class Solution
{
public Node head, tail;
void addNodeToRight(int num)
{
//create a new node after tail
tail.right = new Node(num);
//set the previous pointer of the new node
tail.right.left = tail;
//move tail
tail = tail.right;
}
void inOrder(Node root)
{
//if root is not null
if (root != null)
{
/*recursion*/
inOrder(root.left);
//add the current node to the end of the linked list
addNodeToRight(root.data);
/*recursion*/
inOrder(root.right);
}
}
Node bToDLL(Node root)
{
//create a dummy node
head = new Node(0);
tail = head;
//recursion call
inOrder(root);
//delete the dummy node and return
head = head.right;
head.left = null;
return head;
}
}