我如何删除分支因数不超过30,40的树

问题描述 投票:0回答:1

如果树的最大分支因子为2,我知道如何逐个节点删除整个树节点。基本上,尽可能地向右移动,然后尝试向左移动。直到达到左右ptr = NULL的地步。如果树的最大分支因子为40,我真的不知道如何在代码中执行此操作。

这是我用于删除和查找树的最高深度的代码。

int FindDepth(Node* root,bool GoingRight,int Depth=0,int DepthCompare=0)
{
if(GoingRight)
{
    // If we have reached an end
if(root->right==NULL){if(Depth>DepthCompare){DepthCompare = Depth;}}
    // If space continue going right 
else{DepthCompare = FindDepth(root->right,true,Depth+1,DepthCompare);}
   // Time for going left
GoingRight=false;
}

if(!GoingRight)
{
    // If we have reached an end
if(root->left==NULL){if(Depth>DepthCompare){DepthCompare=Depth;}}
    // If space try going right
else{DepthCompare = FindDepth(root->left,true,Depth+1,DepthCompare);}
}

delete root;
return DepthCompare;
}

任何提示,如果我的节点最多可以容纳40个孩子。

c++ algorithm binary-search-tree nodes
1个回答
0
投票

应用深度优先搜索在这里看起来很方便。您只需将每个节点的子节点添加到堆栈中,当堆栈不为空时,弹出一个节点并对其执行相同的操作,直到到达可以删除的叶节点为止。

来自geeksforgeeks here的C ++中一个不错的实现。

这里唯一的区别是,您正在将其应用于树,因此无需担心。您应该直接到达叶节点,可以安全地将其删除。

© www.soinside.com 2019 - 2024. All rights reserved.