如何在 java 二叉树中实现通用的顺序遍历



如何为我的二叉树类创建按顺序遍历。我已经查看并尝试了其他示例,但似乎无法获得任何适合我的东西。

以下是到目前为止我对顺序遍历方法的了解:

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();    
    }
}

树节点类

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 对象:

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 对象。

最新更新