如何在Java二叉树中实现泛型有序遍历? [英] How to implement a generic in-order traversal in java binary tree?
问题描述
如何为我的Binary Tree类创建有序遍历.我已经查看并尝试了其他示例,但似乎无法为我工作.
How can I create an in-order traversal for my Binary Tree class. I have looked and tried other examples out there but cant get seem to get anything to work for me.
下面是到目前为止我的有序遍历方法:
Below is what I have so far for my in-order traversal method:
public void inOrder(TreeNode<T> root) {
if(root != null) {
inOrder(root.left());
//Visit the node by Printing the node data
System.out.printf("%d ",root.value());
inOrder(root.right());
}
}
public static void main(String[] args) {
BinaryTree<Integer> tree = new BinaryTree<Integer>();
tree.insert(1);
tree.insert(2);
tree.insert(3);
tree.insert(4);
tree.insert(5);
inOrder(tree.root);
}
但是我似乎在说 BinaryTree< T>类型的inOrder(TreeNode< T>)方法时出错了.不适用于参数(BTree< T>)
.
以下是我的课程:二叉树类
public class BinaryTree<T extends Comparable<? super T>> implements BTree<T> {
private TreeNode<T> root;
/**
* Insert method. Insert a value in the binary tree.
*/
@Override
public void insert(T value) {
if(root == null) { //if tree is empty insert value at root
root = new TreeNode<T>(value);
}else if(value.compareTo(value()) < 0) { //insert value to left as its smaller than the root value
root.left().insert(value);
}else{ //insert value to right as its greater than the root value
root.right().insert(value);
}
}
/**
* Returns the value of a node in the tree.
*/
@Override
public T value() {
return root.value();
}
/**
* Returns the left node in the tree.
*/
@Override
public BTree<T> left() {
return root.left();
}
/**
* Returns the right node in the tree.
*/
@Override
public BTree<T> right() {
return root.right();
}
}
TreeNode类
public class TreeNode<T extends Comparable<? super T>> {
T value;
BTree<T> left, right;
public TreeNode(T value) {
this.value = value;
left = new BinaryTree<T>();
right = new BinaryTree<T>();
}
public T value() {
return value;
}
public BTree<T> left() {
return left;
}
public BTree<T> right() {
return right;
}
}
二叉树接口
public interface BTree<T extends Comparable<? super T>> {
public void insert(T value);
public T value();
public BTree<T> left();
public BTree<T> right();
}
推荐答案
您的问题是,在对 inOrder()
函数的递归调用中,您传递了BTree对象而不是预期的TreeNode对象:
Your problem is that in the recursive call to the inOrder()
function you pass in the BTree objects instead of the expected TreeNode object:
public void inOrder(TreeNode<T> root) {
if(root != null) {
inOrder(root.left()); //Passing in a BTree<T> object instead of TreeNode<T>
System.out.printf("%d ",root.value());
inOrder(root.right()); //Passing in a BTree<T> object instead of TreeNode<T>
}
}
您应该决定还是将存储在TreeNode对象中的左/右值也用作TreeNode类型,或者将访问左/右值的结果强制转换为 inOrder()
中的TreeNode对象功能.
You should decide to either use the left/right values stored in your TreeNode object as type TreeNode too or to cast the result of accessing the left/right values to TreeNode objects in your inOrder()
function.
这篇关于如何在Java二叉树中实现泛型有序遍历?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!