【发布时间】:2022-01-23 20:12:25
【问题描述】:
我有以下代码。 但预计它没有参数,例如 sum(),我不太确定如何解决这个问题,以便代码仍然可以工作。有人可以帮我吗? 我想尽可能少地更改代码。 有没有办法将它添加到方法中并从中调用recusive方法
import java.util.*;
public class BinarySearchTree {
private class BinaryNode {
private int element;
private BinaryNode left;
private BinaryNode right;
private BinaryNode(int element) {
this.element = element;
}
}
private BinaryNode root;
public void insert(int newNumber) {
// special case: empty tree
if (root == null) {
root = new BinaryNode(newNumber);
return;
}
BinaryNode parent = null;
BinaryNode child = root;
while (child != null) {
parent = child;
if (newNumber == child.element) {
//number already in tree
return;
} else if (newNumber < child.element) {
child = child.left;
} else {
child = child.right;
}
}
if (newNumber < parent.element) {
parent.left = new BinaryNode(newNumber);
} else {
parent.right = new BinaryNode(newNumber);
}
}
public int maximumRecursive(BinaryNode root) {
if (root.right == null)
return root.element;
return maximumRecursive(root.right);
}
public int maximumIterative() {
if (root == null) {
throw new NoSuchElementException();
}
BinaryNode current = root;
while (current.right != null)
current = current.right;
return (current.element);
}
public int height(BinaryNode root) {
if (root == null)
return 0;
return 1 + Math.max(height(root.left), height(root.right));
}
public int sum(BinaryNode root) {
if (root == null)
return 0;
return root.element + sum(root.left) + sum(root.right);
}
public String reverseOrder(BinaryNode root) {
if (root == null) {
return "";
}
return reverseOrder(root.right) + " " + ((Integer) root.element).toString() + " " + reverseOrder(root.left);
}
【问题讨论】:
-
两个问题: 1. 如果要求sum没有参数,是不是应该计算树中所有节点的和? 2. 你能确认这是一个学校作业吗?如果没有,为什么不使用 TreeMap?
-
它应该计算二叉搜索树中的所有数字,不仅 sum 不应该没有参数,而是所有的方法。这是大学的作业,但我的代码不适用于网站,我必须使用参数将其提交。
-
您可以将递归函数转换为迭代函数。要重用您当前的逻辑,您可以将这些方法设为私有。然后,您可以添加相应的公共方法,该方法调用通过根的私有方法。例如: public int sum() { return sum(root); } private int sum(BinaryNode root) { ... }
-
@issac,对下面的答案有任何反馈吗?
标签: java binary-search-tree computer-science