开发者

Adding an element to a tree

开发者 https://www.devze.com 2023-03-08 03:17 出处:网络
When I try to add some elements to a tree, I use the following method: void add(City added, City parent){

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

精彩评论

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