2011-05-20 15 views
0

私は、ツリーデータ構造を剪定、次の機能があります。削除するノードを適切

public static void pruneTree(final ConditionTreeNode treeNode) { 

    final List<ConditionTreeNode> subTrees = treeNode.getSubTrees(); 

    for (ConditionTreeNode current : subTrees) { 
     pruneTree(current); 
    } 

    if(subTrees.isEmpty()) { 
     final ConditionTreeNode parent = treeNode.getParent(); 
     parent.removeConditionTreeNode(treeNode); 
    } 

    if (treeNode.isLeaf()) { 
     //this is the base case 
     if (treeNode.isPrunable()) { 
      final ConditionTreeNode parent = treeNode.getParent(); 
      parent.removeConditionTreeNode(treeNode); 
     } 
     return; 
    } 

} 

を、私はこれを剪定するための最良の方法が何であるかを知りたいです。私はConcurrentModificationExceptionsを現在取得しています。コレクションをコピーして元のものを削除したり、イテレータから削除することができます。このメソッドを機能させるために、私が何をする必要があるのか​​を誰かが理解できるように助けることができますか?

答えて

1

問題は、ノードのコレクションを反復し、場合によっては再帰呼び出し内の実際のアイテムをコレクションから削除することです。代わりに、実際の項目が削除されることを示すために反復呼び出しからbooleanフラグを返してからIterator.remove()(これを可能にするためにforeachループを反復ループに変更する必要があります)で削除することができます。

実際のアイテムを唯一のサブノードに置き換えるのは手間がかかります。カスタムクラスを定義して再帰的メソッド呼び出しから詳細情報を返すことはできますが、扱いにくくなり始めます。または、再帰呼び出しを、ループを使用して置き換えることを検討することもできます。スタック。

+0

再帰呼び出しからブール値を返すと、ツリーの正しいレベルでどのように削除できるかわかりません –

0
public boolean remove(int target) 
{ 
    if(find(target)) //TreeNode containing target found in Tree 
    { 
     if(target == root.getInfo()) //target is in root TreeNode 
     { 
      if(root.isLeaf()) 
      root = null; 
     else if(root.getRight() == null) 
      root = root.getLeft(); 
     else if(root.getLeft() == null) 
      root = root.getRight(); 
     else 
     { 
      root.getRight().getLeftMostNode().setLeft(root.getLeft()); 
      root = root.getRight(); 
     } 
     } 
     else //TreeNode containing target is further down in Tree 
     { 
      if(cursor.isLeaf()) //TreeNode containing target has no children 
     { 
      if(target <= precursor.getInfo()) 
       precursor.removeLeftMost(); 
      else 
     precursor.removeRightMost(); 
      } 
     else if(cursor.getRight() == null) //TreeNode containing target   
     {     //has no right subtree 
      if(target <= precursor.getInfo()) 
       precursor.setLeft(cursor.getLeft()); 
      else 
     precursor.setRight(cursor.getLeft()); 
     } 
     else if(cursor.getLeft() == null) //TreeNode containing target 
     {     //has no left subtree 
      if(target <= precursor.getInfo()) 
        precursor.setLeft(cursor.getRight()); 
      else 
     precursor.setRight(cursor.getRight()); 
     } 
     else //TreeNode containing target has two subtrees 
     { 
      cursor.getRight().getLeftMostNode().setLeft(cursor.getLeft()); 
      if(target <= precursor.getInfo()) 
        precursor.setLeft(cursor.getRight()); 
      else 
     precursor.setRight(cursor.getRight()); 
      } 
     } 

     cursor = root; 
     return true; 
    } 
    else //TreeNode containing target not found in Tree   
     return false; 
} 
関連する問題