-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaddonetotree.java
126 lines (102 loc) · 2.56 KB
/
addonetotree.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
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
116
117
118
119
120
121
122
123
124
125
126
package trees;
import java.util.ArrayDeque;
import java.util.Scanner;
public class addonetotree {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public static TreeNode addOneRow(TreeNode root, int v, int d) {
if (d == 0) {
return root;
}
if (d == 1) {
TreeNode node = new TreeNode(v);
node.left = root;
return root;
}
addOneRowhelp(root, d, v, 1);
return root;
}
public static void addOneRowhelp(TreeNode node, int tl, int v, int cl) {
if (node == null) {
return;
}
if (cl == tl) {
return;
}
if (cl == tl - 1) {
TreeNode temp = node.left;
node.left = new TreeNode(v);
node.left.left = temp;
TreeNode temp2 = node.right;
node.right = new TreeNode(v);
node.right.right = temp2;
} else {
addOneRowhelp(node.left, tl, v, cl + 1);
addOneRowhelp(node.right, tl, v, cl + 1);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int v, d;
String line1 = sc.nextLine().trim();
String line2 = sc.nextLine().trim();
Integer[] vd = inputSplitSpace(line1);
v = vd[0];
d = vd[1];
Integer[] treeArr = inputSplitSpace(line2);
TreeNode root = createTree(treeArr);
TreeNode res = addOneRow(root, v, d);
display(res);
}
// utility function to display a binary tree.
public static void display(TreeNode node) {
if (node == null) {
return;
}
String str = "";
str += node.left == null ? "." : node.left.val;
str += " <= " + node.val + " => ";
str += node.right == null ? "." : node.right.val;
System.out.println(str);
display(node.left);
display(node.right);
}
// utility function, don't change its code
public static Integer[] inputSplitSpace(String str) {
String[] sArr = str.split(" ");
Integer[] arr = new Integer[sArr.length];
for (int i = 0; i < arr.length; i++) {
arr[i] = sArr[i].equals("null") ? null : Integer.parseInt(sArr[i]);
}
return arr;
}
// utility function to create a tree, don't change its code.
public static TreeNode createTree(Integer[] arr) {
ArrayDeque<TreeNode> que = new ArrayDeque<>();
TreeNode root = new TreeNode(arr[0]);
que.addLast(root);
int i = 1;
while (!que.isEmpty() && i < arr.length) {
TreeNode nn = que.removeFirst();
if (i < arr.length && arr[i] != null) {
TreeNode n = new TreeNode(arr[i]);
nn.left = n;
que.addLast(n);
}
i++;
if (i < arr.length && arr[i] != null) {
TreeNode n = new TreeNode(arr[i]);
nn.right = n;
que.addLast(n);
}
i++;
}
return root;
}
}