如何在java中从右到左遍历二叉树?

How can i traverse a binary tree from right to left in java?

我想从右到左遍历二叉树并将具有相同姓氏的每个项目添加到队列中。我已经正确地实现了一个队列列表 class 和一个树节点 class 但是,当我试图找到一些东西时,我得到了一个空指针异常。 (当然我已经写了一个二叉树的插入方法)。

public class ST {


    private TreeNode root;
    private int size;
    private Queue q;


    public Queue searchByLastName(String last_name) {
            searchByLastNameRec(this.root, last_name);
            return q;
        }

        private void searchByLastNameRec(TreeNode newroot, String last_name) {
            if (newroot == null)
                return;
            if (newroot.right != null) {
                if (newroot.right.item.getLast_name().equalsIgnoreCase(last_name)) {
                    q.put(newroot.right.item);
                }
                searchByLastNameRec(newroot.right, last_name);
            }
            if (newroot.left != null) {
                if (newroot.left.item.getLast_name().equalsIgnoreCase(last_name)) {
                    q.put(newroot.left.item);
                }
                searchByLastNameRec(newroot.left, last_name);
            }
        }


public class TreeNode {
    Suspect item;
    TreeNode left, right, parent;
    int N;

    public TreeNode(Suspect item) {
        if (item == null)
            throw new IllegalArgumentException();
        this.item = item;

    }

}

我猜您树中的某些项目为空,或者某些项目的姓氏为空。由于您在构建节点时检查是否为空项,因此我倾向于后者。

试试这个:

public TreeNode(Suspect item) {
    if (item == null)
        throw new IllegalArgumentException();
    if (item.getLast_name() == null)
        throw new IllegalArgumentException();
    this.item = item;
}

试试这个

private void searchByLastNameRec(TreeNode newroot, String last_name) {
    if (newroot == null || newroot.item == null)
        return;
    if (Objects.equals(last_name, newroot.item.getLast_name()))
        q.put(newroot.item);
    searchByLastNameRec(newroot.right, last_name);
    searchByLastNameRec(newroot.left, last_name);
}