'simplification of function signature in Java
I want to "simplify" the signature of functions, but I'm not sure if this action is possible. If anyone can help me I will be very grateful.
Could anyone help me how to transfer the code from this:
(In the main Main class I wrote the lines below)
Tree tree = new Tree(15);
int[] set1 = {15, 21, 8, 41, 8, 5, 41, 33};
int[] set2 = {18, 45, 36, 19, 3, 24, 19, 10};
for (int i = 0; i < set1.length; i++) {
tree.add(tree, set1[i]);
}
System.out.println("The depth of the tree is " + tree.depth(tree) + ".");
I want to remove the input (Tree tree) for the functions of the Tree class, if this action is possible:
Tree tree = new Tree(15);
int[] set1 = {15, 21, 8, 41, 8, 5, 41, 33};
int[] set2 = {18, 45, 36, 19, 3, 24, 19, 10};
for (int i = 0; i < set1.length; i++) {
tree.add(set1[i]);
}
System.out.println("The depth of the tree is " + tree.depth() + ".");
Tree class:
public class Tree {
/**
* The value of this node in the tree.
*/
public int node;
/**
* The left subtree.
*/
private Tree lhs;
/**
* The right subtree.
*/
private Tree rhs;
/**
* Creates a new tree with the value node.
* @param node The value of this node in the tree.
*/
public Tree(int node) {
this.node = node;
this.lhs = null;
this.rhs = null;
}
public void add(Tree tree, int insert) {
addRecursive(tree, insert);
}
private Tree addRecursive(Tree current, int value) {
if (current == null) {
return new Tree(value);
}
if (value < current.node) {
current.lhs = addRecursive(current.lhs, value);
} else if (value > current.node) {
current.rhs = addRecursive(current.rhs, value);
} else {
// value already exists
return current;
}
return current;
}
public int depth(Tree tree) {
// Root being null means tree doesn't exist.
if (tree == null)
return 0;
// Get the depth of the left and right subtree
// using recursion.
int leftDepth = depth(tree.lhs);
int rightDepth = depth(tree.rhs);
// Choose the larger one and add the root to it.
if (leftDepth > rightDepth)
return (leftDepth + 1);
else
return (rightDepth + 1);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
