【问题标题】:Comparing two valus of Nodes in Binary search trees in java比较java中二叉搜索树中节点的两个值
【发布时间】:2021-04-26 18:16:28
【问题描述】:

嘿,我是二叉树世界的新手,我正在尝试与值进行比较,以了解接下来应该将新添加的节点放置在哪个方向。 现在,我尝试使用 CompareTo 方法,但没有成功我现在正在尝试创建一个私有方法,该方法将为我提供节点的价值,我希望得到一些帮助 这是我的代码,现在我需要在 if 语句中添加节点比较,以便继续:

public void add(E data) {
    if(root == null) {
        return ;
    }
    if(root.getLeftSon() == null) {
        root.setLeftSon((Node<E>) data);
    }
    else if(root.getRightSon() == null) {
        root.setRightSon((Node<E>) data);
    }

}

【问题讨论】:

  • 您的数据是 E 类型,我假设您的根是 Node 类型。为什么要将数据转换为 Node 类型?您可以让每个节点都有一个节点类型的左右子节点和一个 E 类型的数据字段。这样,您可以创建一个节点,其值可以是您希望树保存的任何类型的值。

标签: java tree binary


【解决方案1】:

您必须正确使用泛型。参数必须扩展可比较,以便您确定如何对其进行排序。

class BinaryTree<T extends Comparable<T>> {
    Node<T> root;

    public Node<T> addRecursive(Node<T> current, T value) {
        if (current == null) {
            return new Node<T>(value);
        }

        int ord = value.compareTo(current.value);

        if (ord > 0) {
            current.left = addRecursive(current.left, value);
        } else if (ord < 0) {
            current.right = addRecursive(current.right, value);
        } else {
            // value already exists
            return current;
        }

        return current;
    }

    static class Node<T extends Comparable<T>> {
        T value;
        Node<T> left;
        Node<T> right;

        Node(T value) {
            this.value = value;
            right = null;
            left = null;
        }
    }
}

【讨论】:

  • 为了完美添加包含root = addRecursive(root, value)的原始add
猜你喜欢
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
相关资源
最近更新 更多