开发者

How can one add a specific part of a binary tree but keep the tree intact (Java)?

开发者 https://www.devze.com 2023-03-18 04:58 出处:网络
I am trying to write a code that searches a binary tree for an element and then adds starting at that element. So far I can find the correct position and add to that position, but I lose the rest of t

I am trying to write a code that searches a binary tree for an element and then adds starting at that element. So far I can find the correct position and add to that position, but I lose the rest of the binary tree.

    public void add(String addroot, String addleft)
      if(root!=nodesearch){
        if(root.left!=null){
          root=root.left;
          add(addroot, addleft);
        }
        if(root.right!=null){
          root=root.right;
          add(addroot, addleft);
        }
      }
  开发者_开发技巧    else
        root=insert();
    }

insert() adds the elements and it works fine. Thanks for any help.

Ok so this is what I'm thinking now.

private BinaryStringNode local_root = root
public void add()

  if(root!=nodesearch){
    if(local_root.left!=null){
      local_root=local_root.left;
      add();
    }
    if(local_root.right!=null){
      local_root=local_root.right;
      add();
    }
  }
  else
    local_root=insert();
}

Would local_root=insert() use the insert method on root at the position of local_root. Also would local_root=local_root.right move through root?


First Make it three independent functions

void insert(BinaryStringNode root, BinaryStringNode new_node){

}

int add(BinaryStringNode root){

}

BinaryStringNode find(String name){

}

Now fill the code in as best you can.

When you want to get the sum just call add(find(s)); where s is a string

0

精彩评论

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