java - 二叉树中通用节点的Java数组,无法创建零节点
问题描述
我遇到了与此问题类似的问题: Array of generic nodes Java
然而,使嵌套的 Node 类静态解决了一个问题,但为我创建了另一个问题。我写了一个二叉树,每次节点的指针不应该指向任何东西(例如叶节点的左右指针或根的父指针)时,它实际上指向一个特殊的“nil”节点,其中不包含相关数据。Nil 是二叉树的成员变量。
当我创建一个节点时,构造函数使所有指针都指向 nil。但是,如果我将 Node 类设为静态,以便创建节点数组(我需要为特定方法执行此操作),我会收到每个指针的错误消息“无法对非静态字段进行静态引用零。” 但是,如果我将 nil 更改为静态,我会得到一个错误,上面写着“无法对非静态类型 T 进行静态引用”。(我的节点保存参数化类型对象。)
这是我的节点类:
protected static class Node<T>{
Node left, right, parent;
T object;
protected Node(T x) {
object= x;
left= nil;
right= nil;
parent= nil;
}
}
这是 nil 指定和二叉树构造函数,它创建 nil 节点并使其成为根:
protected static Node<T> nil;
public BT() {
nil= new Node<T>(null);
root= nil;
}
我如何允许自己创建节点数组而不会遇到这些静态与非静态问题?
解决方案
First, never use raw generics, so specify <T>
on the Node
fields:
protected static class Node<T> {
Node<T> left, right, parent;
T object;
Next, to initialize nil
, you need a difference constructor:
protected Node() {
left = this;
right = this;
parent = this;
}
Now you can initialize nil
as a non-static object, to keep type-safety:
protected Node<T> nil = new Node<>();
Though, rather than creating a nil
object for every tree, create a static method:
@SuppressWarnings("rawtypes")
private static Node NIL = new Node();
@SuppressWarnings({ "cast", "unchecked" })
protected static <T> Node<T> nil() {
return (Node<T>) NIL;
}
推荐阅读
- python - 储蓄情绪分析模型
- r - 与多变量条件 R 配对
- google-chrome-extension - 为什么我没有收到来自 Node.JS Native App 到我的 chrome 扩展的任何消息?
- forms - MS Access:显示存储在表格中的图片/徽标作为附件
- wordpress - Wordpress - 按分类挂钩预加载术语页面
- ruby-on-rails - 在 Raisl 6 中从 git 中删除 node_modules 后推送失败
- windows - 如何修复 CURL 错误“无法解析主机”?
- r - 如何在保持R格式的同时将表达式转换为字符
- c++ - 当 std::optional 和 boost::optional 的值是变体时的区别
- java - Cordova 应用程序在从另一个活动返回时使用回调时崩溃