Reputation: 3
Forgive me if this makes no sense at all, but I am just learning. I have stumbled across a piece of code that traverses a binary tree using a level search. I understand mostly the logic behind it but there are parts that confuse me, mainly 3 lines -
Node left, right;
in the Node class. Am I correct that we are just making variables of this class type?
Node root;
in the BinaryTree class. Is this an object of type Node? I thought you had to instantiate the class to have the object?
tree_level.root.left.right = new Node(5);
I have no clue what is going on here. I understand that tree_level is the object and that through that object it can access the root variable, but then how is root able to access multiple left and right variables from the Node class.
I guess I'm more confused over how the two classes relate without any instantiation and I don't see any static code either.
package com.company;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import org.w3c.dom.ls.LSOutput;
import java.util.Queue;
import java.util.LinkedList;
class Node{
int data;
Node left, right;
public Node(int item){
data = item;
left = null;
right = null;
}
}
public class BinaryTree {
Node root;
public void printLevelOrder(){
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while(!queue.isEmpty()){
System.out.println("While loop starts...");
for(Node s : queue) {
System.out.println("Loop: " + s.data);
}
Node tempNode = queue.poll();
System.out.println(tempNode.data + " ");
if(tempNode.left != null){
queue.add(tempNode.left);
}
if(tempNode.right != null){
queue.add(tempNode.right);
}
}
}
public static void main(String[] args) {
BinaryTree tree_level = new BinaryTree();
tree_level.root = new Node(1);
tree_level.root.left = new Node(2);
tree_level.root.right = new Node(3);
tree_level.root.left.left = new Node(4);
tree_level.root.left.right = new Node(5);
System.out.println("The level order traversal of the binary tree is: ");
tree_level.printLevelOrder();
}
}
Upvotes: 0
Views: 126
Reputation: 117
I'll try to answer your questions.
Node left, right; in the Node class. Am I correct that we are just making variables of this class type?
Yes, that's correct. After that declaration, your class Node has two new attributes Node left and Node right.
Node root; in the BinaryTree class. Is this an object of type Node?
Yes, this is an instantiation of a Node with the value null. From the Java Language Specification, section 4.12.5:
Initial Values of Variables
Every variable in a program must have a value before its value is used:
Each class variable, instance variable, or array component is initialized with a default > value when it is created
[...] For all reference types, the default value is null.
tree_level.root.left.right = new Node(5)
A new object of type Node is being placed inside a BinaryTree. This Node has a value of 5. In this case is something like this:
Upvotes: 2