Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BinaryNode {
- int value;
- //setting up binarynode values
- private BinaryNode left;
- private BinaryNode right;
- public BinaryNode(int value) {
- this.value=value;
- left = null;
- right = null;
- }
- public void setLeft(BinaryNode left) {
- this.left = left;
- }
- public void setRight(BinaryNode right) {
- this.right = right;
- }
- public void setValue(int value) {
- this.value = value;
- }
- public BinaryNode getLeft() {return left;}
- public BinaryNode getRight() {return right;}
- public int getValue() {return value;}
- }
- public class BinaryTree {
- BinaryNode root;
- public BinaryNode getRoot(){return root;}
- public void insertNode(int newInt, BinaryNode currentNode) {
- if (root == null) {
- root = new BinaryNode(newInt);
- //System.out.println(currentNode);
- //System.out.println(newInt);
- //System.out.println(newInt.getValue());
- //System.out.println("Node Null, made root");
- }else{
- //if less than the node, go left
- if (newInt < currentNode.getValue()) {
- //System.out.println("less than");
- if (currentNode.getLeft() == null) {
- //System.out.println("Node Null, set left");
- currentNode.setLeft(new BinaryNode(newInt));
- }
- //the recursive call on insert
- else {
- //System.out.println("recursive left");
- insertNode(newInt, currentNode.getLeft());
- }
- }
- else {
- //if greater than node, and
- //System.out.println("greater than");
- if (currentNode.getRight() == null) {
- //System.out.println("Node Null, set right");
- currentNode.setRight(new BinaryNode(newInt));
- }
- else {
- //System.out.println("recursive right");
- insertNode(newInt, currentNode.getRight());
- }
- }
- }
- }//insertNode body
- public void outputList() {
- //create output string
- String listoutput =("");
- traverse(root);
- System.out.println(listoutput);
- }
- public String traverse(BinaryNode node) {
- //first a recursive call on the left subtree, if it exists
- if (node.getLeft() != null) {
- traverse(node.getRight());
- }
- //add current node to outString
- append(node.getValue());
- //followed by a recursive call on the right subtree, if it exists
- if(node.getRight() != null) {
- traverse(node.getRight());
- }
- }
- public void append(String newString){
- if (listoutput.equals("")){
- listoutput += newString;
- } else {
- listoutput += ", " + newString;
- }
- }
- public static void main(String[] args) {
- //input from command line
- BinaryTree input = new BinaryTree();
- for (String arg : args) {
- input.insertNode(Integer.parseInt(arg), input.getRoot());
- }
- input.outputList();
- }
- }//class body
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement