I need to create an unsorted binary tree (one requirement is that it is unsorted) that holds a String
as its value. My class outline looks like this:
public class Node {
private String desc;
private Node leftNode = null;
private Node rightNode = null;
public Node(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
public Node getLeftNode() {
return leftNode;
}
public Node getRightNode() {
return rightNode;
}
}
Eventually I want to be able to replace any node that matches a String
description with a new node that has a new description (including duplicates with the old description).
So my question is, what is the best way to handle the insertion of Node
s when creating an unsorted binary tree?
I thought of two ways. The first would be to just have two methods, setLeftNode(Node root, String desc)
and setRightNode(Node root, String desc)
that someone could call with a Node
of their choice as the root. If there already is a left/right Node
, then it would just advance down until it hit a node that didn't have a left Node
. But this could introduce problems by producing super large heights.
The second way I thought of would be to have a dedicated root Node
, in this case the first Node
created, and then to just build new Node
s in order.
So what is the best way to create an unsorted binary tree?