[英]How to implement a generic in-order traversal in java binary tree?
如何為二叉樹類創建有序遍歷。 我已經看過並嘗試了其他示例,但似乎無法為我工作。
以下是到目前為止我的有序遍歷方法:
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);
}
但是我似乎正在錯誤地指出The method inOrder(TreeNode<T>) in the type BinaryTree<T> is not applicable for the arguments (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 inOrder()
函數時,您傳遞的是BTree對象而不是預期的TreeNode對象:
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()
函數中將訪問左/右值的結果inOrder()
為TreeNode對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.