开发者

Adding an element to a tree

When I try to add some elements to a tree, I use the following method:

void add(City added, City parent){
    //parentNode is where the element should be added
    TreeNode<City> parentNode = search(parent,this);
开发者_运维问答    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));
    }
}

Yet, the problem is the that when I call the method with "this", I guess the main tree does not change. For instance, when the tree consists of one element, I am able to add any element I want correctly. However, say my tree consists of integer 1, forget about the other stuff. When I add 2 to my tree, no problem. But when I want to add 3 as the child of 2, my code sucks!

Should I use a root and if so, how should I implement it?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜