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

时间:2016-01-14 23:50:34

标签: java binary-tree

我想从右到左遍历二叉树,并将每个具有相同姓氏的项目添加到队列中。我已经正确实现了Queue List类和Tree Node类,但是当我尝试查找某些内容时,我得到一个空指针异常。 (当然我已经为二叉树编写了一个插入方法)。

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;

    }

}

2 个答案:

答案 0 :(得分:2)

试试这个

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

答案 1 :(得分:0)

我猜你树中的一些项目是空的,或者有些项目是空的姓氏。由于在构造节点时检查了空项,因此我倾向于后者。

试试这个:

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