gpt4 book ai didi

java - java 遍历二叉搜索树

转载 作者:太空宇宙 更新时间:2023-11-04 11:58:19 24 4
gpt4 key购买 nike

有人可以告诉我如何循环二叉树以遍历所有节点吗?我将通过插入方法添加学生。我只想打印所有学生对象。这是我的 BST:

public class BinarySearchTree<Students extends Comparable<? super Student>> {
public static BinaryNode root;

public BinarySearchTree() {
this.root = null;
}

public void insert(Student student) {

root = insert(student, root);
}

protected BinaryNode<Student> insert(Student student, BinaryNode<Student> t) {
if (t == null) {

t = new BinaryNode<Student>(student);
} else if (student.compareTo(t.element) < 0) {
t.left = insert(student, t.left);
} else if (student.compareTo(t.element) > 0) {
t.right = insert(student, t.right);
} else {
// throw new DuplicateItemException(student.toString());
}
return t;
}
}

节点类:

class BinaryNode<Student> {
// Constructor
BinaryNode(Student theElement) {
element = theElement;
left = right = null;
}

// Data; accessible by other package routines
Student element; // The data in the node
BinaryNode<Student> left; // Left child
BinaryNode<Student> right; // Right child
}

最佳答案

将此方法添加到 BinarySearchTree 类中:

public void inorder(BinaryNode node) {
if (node == null) {
return;
}
inorder(node.left);
System.out.print(...); //whatever you want to do with the node
inorder(node.right);
}

以类似的方式,您可以进行预序后序遍历。

关于java - java 遍历二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41165552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com