Java二进制树添加方法覆盖写入根

时间:2013-01-24 02:10:26

标签: java recursion binary-tree

我正在尝试编写二叉树,并且add方法不断覆盖树的根。我有两个方法,一个递归的add方法,它接受一个String和一个Node,然后是一个简单调用递归方法的常规add方法。任何帮助将不胜感激。

public   Node recAdd(String event , Node tNode ){
//tNode -> tree node         
  if (tNode == null){
  // Addition place found
    root = new Node(event); 
    System.out.println("added root");
  }
  else if (tNode.event.compareTo(event) <= 0){
   tNode.setLeft(recAdd(event, tNode.getLeft()));   
   // System.out.println("added left");// Add in left subtree
  }
  else{
    tNode.setRight(recAdd(event, tNode.getRight()));
    //   System.out.println("added right");
  }// Add in right subtree
  return tNode;
}

////////////////////////////////////////////// < / p>

public  void add(String event){
  if(root != null){
    System.out.println("The root currently is " + root.event );
   }
   recAdd(event , root);
}

我的节点类如下

public class Node {
  Node left;
  Node  right;
  String event;

  Node(String event){
    this.event = event;
    this.left = null;
    this.right = null;  
  }

  public void setEvent(String event){
    this.event = event;
  } 
  public void setLeft(Node left){
    this.left = left;
  } 
  public void setRight(Node right){
    this.right = right;
  } 

  public  String getEvent(){
    return event;
  }

  public Node getLeft(){
    return left;
  }
  public Node getRight(){
    return right;
  }
}    

2 个答案:

答案 0 :(得分:1)

每当找到插入当前节点的位置时,您将替换根节点:

public Node recAdd(String event, Node tNode) {
    //tNode -> tree node         
    if (tNode == null) {
      // Addition place found
      root = new Node(event);     // Problem is RIGHT HERE
      System.out.println("added root");
    }
  //...
}

答案 1 :(得分:0)

发生的事情是您递归搜索树,直到到达尚未分配的节点(即null)。此时,您将覆盖root而不是创建新节点。

例如:

        root
       /    \
    node     null <- You want to assign this node, not overwrite root
   /    \ 
 null   null

要做到这一点:

public   Node recAdd(String event , Node tNode ){       
    if (tNode == null){
        tNode = new Node(event);  // <--- Don't overwrite root
    }
    else if (tNode.event.compareTo(event) <= 0){
        tNode.setLeft(recAdd(event, tNode.getLeft()));   
    }
    else{
        tNode.setRight(recAdd(event, tNode.getRight()));
    }
    return tNode;
}

您还需要修改add()功能:

public  void add(String event){
    root = recAdd(event , root); // <-----Reassign root
}