正确地从树中删除节点

| 我有以下修剪树数据结构的功能:
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,并且我已经读到可以复制集合并删除原始集合,也可以从迭代器中删除。有人可以帮助我了解我需要做些什么才能使这种方法起作用吗?     
已邀请:
问题是,您要遍历节点的集合,并且在某些情况下,需要在递归调用中从集合中删除实际项。您可以从递归调用中返回一个布尔值标志,以指示要删除的实际项目,然后通过ѭ1remove将其删除(您需要将foreach循环更改为迭代器循环,以实现此目的)。 用唯一的子节点替换实际项比较棘手-您可以定义一个自定义类以从递归方法调用中返回更多信息,但开始变得笨拙。或者您可以考虑使用例如,用循环替换递归调用一个堆栈。     
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;
}
    

要回复问题请先登录注册