java如何实现树节点
实现树节点的基本结构
在Java中,可以通过定义一个类来表示树节点。该类通常包含数据字段和子节点引用。以下是一个基本的树节点实现示例:
class TreeNode {
int val;
List<TreeNode> children;
public TreeNode(int val) {
this.val = val;
this.children = new ArrayList<>();
}
public void addChild(TreeNode child) {
children.add(child);
}
}
二叉树节点的实现
对于二叉树,每个节点最多有两个子节点(左子节点和右子节点)。以下是二叉树的节点实现:

class BinaryTreeNode {
int val;
BinaryTreeNode left;
BinaryTreeNode right;
public BinaryTreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
通用树节点的实现
通用树节点可以包含任意数量的子节点。通常使用一个列表来存储子节点:

class GenericTreeNode<T> {
T data;
List<GenericTreeNode<T>> children;
public GenericTreeNode(T data) {
this.data = data;
this.children = new ArrayList<>();
}
public void addChild(GenericTreeNode<T> child) {
children.add(child);
}
}
带父节点引用的实现
某些场景下需要在节点中包含对父节点的引用:
class TreeNodeWithParent {
int val;
TreeNodeWithParent parent;
List<TreeNodeWithParent> children;
public TreeNodeWithParent(int val) {
this.val = val;
this.parent = null;
this.children = new ArrayList<>();
}
}
树的操作方法
实现树节点后,通常需要实现一些基本的树操作方法:
// 计算树的高度
public int getHeight(TreeNode root) {
if (root == null) return 0;
int maxHeight = 0;
for (TreeNode child : root.children) {
maxHeight = Math.max(maxHeight, getHeight(child));
}
return maxHeight + 1;
}
// 前序遍历
public void preOrderTraversal(TreeNode root) {
if (root == null) return;
System.out.print(root.val + " ");
for (TreeNode child : root.children) {
preOrderTraversal(child);
}
}
使用场景选择
- 二叉树适合二叉搜索树、堆等数据结构
- 通用树适合表示文件系统、组织结构等
- 带父节点引用适合需要频繁回溯的场景






