MCPcopy Create free account
hub / github.com/PrajaktaSathe/Java / buildTree

Method buildTree

Programs/BinaryTreeInorder.java:49–103  ·  view source on GitHub ↗
(String str)

Source from the content-addressed store, hash-verified

47class GfG {
48
49 static Node buildTree(String str) {
50
51 if (str.length() == 0 || str.charAt(0) == 'N') {
52 return null;
53 }
54
55 String ip[] = str.split(" ");
56 // Create the root of the tree
57 Node root = new Node(Integer.parseInt(ip[0]));
58 // Push the root to the queue
59
60 Queue<Node> queue = new LinkedList<>();
61
62 queue.add(root);
63 // Starting from the second element
64
65 int i = 1;
66 while (queue.size() > 0 && i < ip.length) {
67
68 // Get and remove the front of the queue
69 Node currNode = queue.peek();
70 queue.remove();
71
72 // Get the current node's value from the string
73 String currVal = ip[i];
74
75 // If the left child is not null
76 if (!currVal.equals("N")) {
77
78 // Create the left child for the current node
79 currNode.left = new Node(Integer.parseInt(currVal));
80 // Push it to the queue
81 queue.add(currNode.left);
82 }
83
84 // For the right child
85 i++;
86 if (i >= ip.length) break;
87
88 currVal = ip[i];
89
90 // If the right child is not null
91 if (!currVal.equals("N")) {
92
93 // Create the right child for the current node
94 currNode.right = new Node(Integer.parseInt(currVal));
95
96 // Push it to the queue
97 queue.add(currNode.right);
98 }
99 i++;
100 }
101
102 return root;
103 }
104
105 public static void main(String[] args) throws IOException {
106 BufferedReader br =

Callers 1

mainMethod · 0.95

Calls 5

lengthMethod · 0.80
peekMethod · 0.80
equalsMethod · 0.80
addMethod · 0.65
sizeMethod · 0.45

Tested by

no test coverage detected