I am extremely new to java, and all my other searches lead to something more complex than my given question so I was wondering how i may go about this? i would like for my tree nodes to have consist of the following fields: parent, left, right and data.
1 Answer
Since you're new to Java the most basic structure would be like this:
public class Node {
private Node parent, left, right;
private Integer data;
public Node(Node parent, Node left, Node right, Integer data) {
this.parent = parent;
this.left = left;
this.right = right;
this.data = data;
}
public Node getParent() { return this.parent; }
public Node getLeft() { return this.left; }
public Node getRight() { return this.right; }
public Integer getData() { return this.data; }
public void setParent(Node parent) { this.parent = parent; }
public void setLeft(Node left) { this.left = left; }
public void setRight(Node right) { this.right = right; }
public void setData(Integer data) { this.data = data; }
}
If you want to take it one step further and learn more about Object-Oriented Programming I would look into generics.
public class Node<T extends Comparable<T>> {
private Node parent, left, right;
private T data;
// Getters, setters, compare methods here
}
This will let you declare a Node<Integer>, Node<String>, Node<CustomClass> to let you not be restricted to a certain type of data. You'll want to do extend Comparable<T> so that you can easily compare objects when doing an insert(), and other Tree functions.
2 Comments
Adam Davies
to make multiple tree nodes, I'd just have to write this up again with a different node name after that bit of code above? eg. node 1?
Matthew Brzezinski
If you want to make variables for those Nodes, then yes you would want to do something like
Node node1 = new Node(...), Node node2 = new Node(...), etc. But since you're making a BinaryTree I would highly recommend you make public class BinaryTree, which will hold your root Node (which then points to more nodes), and having some methods for insert, delete, search. Here's a link to an implementation of the full thing: stackoverflow.com/a/9955083/1327636