예제 #1
0
  public static void insert(TreeNode tnode, int x, TreeNode p) {
    if (tnode == null) {
      tnode = new TreeNode();
      tnode.value = x;
      tnode.lchild = null;
      tnode.rchild = null;
      if (p.value > x) p.lchild = tnode;
      else p.rchild = tnode;
      tnode.parent = p;
      return;
    }

    if (x < tnode.value) {
      insert(tnode.lchild, x, tnode);
    } else {
      insert(tnode.rchild, x, tnode);
    }
  }
예제 #2
0
파일: TDTree.java 프로젝트: CDargis/TDTree
 /**
  * Private method created for inserting into the tree. Works recursively returns false if point
  * already in tree Method for inserting a node into the tree. Works by traversing through the
  * tree, branches off x value for even cuts, and y for odd cuts. Uses other value as a tie
  * breaker. Also keeps track of height and size for constant return time on those function calls.
  */
 private boolean insert(TreeNode t, TreeNode prev, TreeNode newNode, boolean cd, boolean left) {
   if (t == null) { // Found where node should live
     if (left) {
       prev.left = newNode;
     } else {
       prev.right = newNode;
     }
     newNode.cd = cd;
     newNode.parent = prev;
     size++;
     return true;
   } else if (t.p.equals(newNode.p)) return false; // Found the point, don't insert it
   // Recursive calls to left or right tree
   else if (cd) {
     if (newNode.p.x() < t.p.x()) insert(t.left, t, newNode, !cd, true);
     else if (newNode.p.x() > t.p.x()) insert(t.right, t, newNode, !cd, false);
     else { // Tie breaker
       if (newNode.p.y() < t.p.y()) insert(t.left, t, newNode, !cd, true);
       else insert(t.right, t, newNode, !cd, false);
     }
   } else {
     if (newNode.p.y() < t.p.y()) insert(t.left, t, newNode, !cd, true);
     else if (newNode.p.y() > t.p.y()) insert(t.right, t, newNode, !cd, false);
     else { // Tie breaker
       if (newNode.p.x() < t.p.x()) insert(t.left, t, newNode, !cd, true);
       else insert(t.right, t, newNode, !cd, false);
     }
   }
   updateMinMax(t, newNode);
   t.height = maxHeight(t.left, t.right) + 1;
   // Now check if tree became unbalanced
   if (unbalanced(t)) {
     // System.out.println("unbalanced");
     Point[] points = collectSatanSpawn(t);
     TDTree newSubTree = new TDTree(points, cd);
     swapDataMembers(t, newSubTree.root);
   }
   return true;
 } // End private insert() method