I'm a little bit confused as to understanding how recursion works.
Basically I have to replace recursive methods with non recursive methods.
For example, this is the recursive method:
public Key min() {
if (isEmpty()) {
return null;
}
return min(root).key;
}
private Node min(Node x) {
if (x.left == null) {
return x;
} else {
return min(x.left);
}
}
public Key max() {
if (isEmpty()) {
return null;
}
return max(root).key;
}
private Node max(Node x) {
if (x.right == null) {
return x;
} else {
return max(x.right);
}
}
public Key floor(Key key) {
Node x = floor(root, key);
if (x == null) {
return null;
} else {
return x.key;
}
}
private Node floor(Node x, Key key) {
if (x == null) {
return null;
}
int cmp = key.compareTo(x.key);
if (cmp == 0) {
return x;
}
if (cmp < 0) {
return floor(x.left, key);
}
Node t = floor(x.right, key);
if (t != null) {
return t;
} else {
return x;
}
}
public Key ceiling(Key key) {
Node x = ceiling(root, key);
if (x == null) {
return null;
} else {
return x.key;
}
}
private Node ceiling(Node x, Key key) {
if (x == null) {
return null;
}
int cmp = key.compareTo(x.key);
if (cmp == 0) {
return x;
}
if (cmp < 0) {
Node t = ceiling(x.left, key);
if (t != null) {
return t;
} else {
return x;
}
}
return ceiling(x.right, key);
}
And this is my attempt of doing it non-recursively:
public Key min() {
if (isEmpty()) {
return null;
}
return min(root).key;
}
private Node min(Node x) {
while (x.left !=null){
x = x.left;
}
return x;
}
public Key max() {
if (isEmpty()) {
return null;
}
return max(root).key;
}
private Node max(Node x) {
while (x.right!=null){
x = x.right;
}
return x;
}
public Key floor(Key key) {
Node x = floor(root, key);
if (x == null) {
return null;
} else {
return x.key;
}
}
private Node floor(Node x, Key key) {
if (x == null) {
return null;
}
int cmp = key.compareTo(x.key);
if (cmp == 0) {
return x;
}
if (cmp < 0) {
while (x.left != null){
x = x.left;
if (x ==null){
return null;
}
}
}
Node t = x.right;
while (x.right != null){
x = x.right;
if (x == null){
return null;
}
}
if (t != null){
return t;
}
else{
return x;
}
}
I'm just asking if I have the right idea.