我想将第二个树插入到与其根名称相同的节点中的第一个树中,并将此节点的子节点附加到第二个树的最左边的子节点。
我试过了:
PTree attachPoint = chain.Find(x => x.Val == RTree.Val);
if (attachPoint != null)
{
foreach (var c in attachPoint.Childs)
{
RTree.Left.Childs.Add(c);
}
attachPoint = RTree;
}
else
{
RTree.Left.Childs.Add(root);
root = RTree;
}
此处,RTree
是第二个树,root
指向第一个树的根,chain
保存来自root的分支" A"到" D"。但似乎没有建造所需的树。我做得对吗?
答案 0 :(得分:1)
import java.util.ArrayList;
public class Main {
public static ArrayList<String> removeInRange(ArrayList<String> list, String beginning, String ending)
{
for (int i = 0; i<list.size(); i++)
{
if (list.get(i).compareTo(beginning)> 0 && list.get(i).compareTo(ending)< 0)
{
list.remove(list.get(i));
}
else {
System.out.println("Error");
}
} return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("h");
list.add("e");
list.add("x");
removeInRange(list, "a", "k");
}
}
(和attachPoint
?)只是局部变量,因此root
不会影响树的结构。您需要搜索左侧树以查找插入点的父节点,然后修改父节点以便attachPoint = RTree;
答案 1 :(得分:1)
如果你已经包含了PTree
课程的基本部分,那将更容易提供帮助。以下是我根据发布的代码建议您的内容:
PTree attachPoint = chain.Find(x => x.Val == RTree.Val);
if (attachPoint != null)
{
foreach (var c in attachPoint.Childs)
{
RTree.Left.Childs.Add(c);
}
// Here you either have to find the attachPoint parent and
// replace attachPoint with RTree in parent.Childs,
// or make attachPoint.Childs to be RTree.Childs as below
attachPoint.Childs.Clear();
foreach (var c in RTree.Childs)
{
attachPoint.Childs.Add(c);
}
}
else
{
RTree.Left.Childs.Add(root);
root = RTree;
}