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

情到浓时终转凉″ 提交于 2019-12-10 23:33:17

问题


I want to traverse a binary tree from right to left and add to a queue every item with same last name. I have correctly implement a Queue List class and a Tree Node class but, i get a null pointer exception when i try to find something. (Of course i have written an insertion method for the binary tree).

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;

    }

}

回答1:


Try this

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



回答2:


I'm guessing some of the items in your tree are null, or some have null last names. Since you check for a null item when you construct a node, I'm leaning towards the latter.

Try this:

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


来源:https://stackoverflow.com/questions/34801976/how-can-i-traverse-a-binary-tree-from-right-to-left-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!