-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
115 lines (76 loc) · 2.21 KB
/
Copy pathSolution.java
File metadata and controls
115 lines (76 loc) · 2.21 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package trees;
import java.util.Scanner;
class Node<T> {
T data;
Node left;
Node right;
Node parent;
Node next;
Node(T data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}
}
public class Solution {
public static Node helper(int arr[], int i, int n, Node root) {
if (root == null) {
root = new Node(arr[i], null, null);
}
if (2 * i + 1 < n && arr[2 * i + 1] != -1) {
root.left = helper(arr, 2 * i + 1, n, root.left);
}
if (2 * i + 2 < n && arr[2 * i + 2] != -1) {
root.right = helper(arr, 2 * i + 2, n, root.right);
}
return root;
}
public static void inorder(Node root) {
if (root == null) {
return;
}
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
public static void setParent(Node root, Node parent) {
if (root == null) {
return;
}
root.parent = parent;
parent = root;
setParent(root.left, parent);
setParent(root.right, parent);
}
public static Node solve(int[] arr) {
int n = arr.length;
Node root = null;
root = helper(arr, 0, arr.length, root);
// Node parent = null;
// setParent(root, parent);
inorder(root);
return root;
}
public static void display(Node node) {
if (node == null) {
return;
}
String str = "";
str += node.left == null ? "." : node.left.data;
str += " => " + node.data + ("[" + (node.parent != null ? node.parent.data : "null") + "]") + " <= ";
str += node.right == null ? "." : node.right.data;
System.out.println(str);
display(node.left);
display(node.right);
}
public static void main(String[] args) {
Node root = null;
Scanner scn = new Scanner(System.in);
int[] arr = new int[scn.nextInt()];
for (int i = 0; i < arr.length; i++) {
arr[i] = scn.nextInt();
}
root = solve(arr);
display(root);
}
}