开发者

Creating A Tree and Adding Values

Hey guys, I have implemented a tree. To me, it should work properly, but since I am here, it does not. For the record, my tree is of type City, which has three fields, one of which is name as you will see. Take a look at my codes:

void add(City added, City parent){
//added is what is going to be added and child of parent. I first find parent in tree
//search method is coming after
    TreeNode开发者_JS百科<City> parentNode = search(parent,this);
    if (parentNode.hasLeftChild() && parentNode.getLeftChild().getCity().equals(parent))
        parentNode = parentNode.getLeftChild();
    else if (parentNode.hasNextSibling() && parentNode.getNextSibling().getCity().equals(parent))
        parentNode = parentNode.getNextSibling();
    else if (!parentNode.hasLeftChild())
        parentNode.setLeftChild(new TreeNode<City>(added,null,null));
    else {
        TreeNode<City> next = parentNode.getLeftChild();
        while(next.hasNextSibling())
            next = next.getNextSibling();
        next.setNextSibling(new TreeNode<City>(added,null,null));
    }
}

public TreeNode<City> search(City parent, TreeNode<City> t){
    if (t.getCity().equals(parent))
        return t;
    else if (t.hasLeftChild())
        return search(parent,t.getLeftChild());
    else 
        return search(parent,t.getNextSibling());
}

I am keep taking nullpointerexception and have no idea what to do. Anyone has better idea to search for an element and add it. Or at least a web-site for me to learn that shit???


You have to test for the base case where your tree is null, so that the Node you are trying to add will really become the root of the tree.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜