【问题标题】:Copying a first child next sibling tree复制第一个孩子的下一个兄弟树
【发布时间】:2012-10-18 18:49:32
【问题描述】:

我已经在 java 中实现了“第一个孩子下一个兄弟”树的类。

这是一个代表这种树的链接

http://www.cs.utexas.edu/~novak/cs315116.html

我实现了以下功能:

addChild();
getLabel(); 
setLabel(T v);
getParent();
getNextSibling();
getFirstChild();

我的 addChild 函数按以下顺序添加子项。

public void addChild(Tree<T> c) {
     c.parent = this;
     if (firstChild == null) 
       firstChild = c;
     else {
         c.nextSibling = firstChild;
         firstChild = c;
        }
}

That is, if we have a tree node 1 and we add tree node 2 and then tree node 3 to it then the final tree would be,
1.addChild(2);
1.addChild(3);

 1                                          1
/ \    which is internally stored as       /
3   2                                      3 - 2
The most recent child added would be the first child

我想实现一个 CopyTree 函数,当给定任何这样的树作为参数时,它将创建树的副本并返回它。 我有一些初始代码,但我无法获得正确的递归。

private Tree<String> CopyTree(Tree<String> tr){
if (tr == null)
    return null;
Tree<String> t = new Tree<String>();
t.setLabel(tr.getLabel());
if (tr.getFirstChild() != null) {
    t.addChild(CopyTree(tr.getFirstChild()));
}
Tree<String> temp = tr.left();

if (temp != null) {
while (temp.getNextSibling() != null) {
    t.addChild(CopyTree(temp.getNextSibling()));
    temp = temp.getNextSibling();
}
}
return t;
}

如何才能使递归工作?

提前致谢

【问题讨论】:

    标签: java recursion tree


    【解决方案1】:

    首先,我相信你这里有一个错误:

     while (temp.getNextSibling() != null) {
        t.addChild(CopyTree(temp.getNextSibling()));
        temp = temp.getNextSibling();
    }
    

    由于 getNextSibling() 将下一个孩子重新调整到右侧,但 addChild() 从左侧插入一个孩子,因此您在这里颠倒了顺序。这可能没问题,但请尽量避免这种情况。

    要回答您的问题,您的递归函数应作为新树的每个节点上的方法调用,并接收旧树的相应节点作为参数。然后它应该从旧树中复制该节点的子节点到新节点中,并在执行此操作时对每个子节点调用递归函数。

    【讨论】:

      【解决方案2】:

      知道了..

      private Tree<String> CopyTree(Tree<String> tr){
      if (tr == null)
          return null;
      Tree<String> t = new Tree<String>();
      t.setLabel(tr.getLabel());
      
      Tree<String> temp = tr.left();
      
      if (temp != null) {
          ArrayList<Tree<String>> list = new ArrayList<>();
          while (temp.getNextSibling() != null) {
          list.add(temp.getNextSibling());
          //t.addChild(CopyTree(temp.getNextSibling()));
          temp = temp.getNextSibling();
      }
      for (int i = (list.size()-1); i>=0; i--) {
          t.addChild(CopyTree(list.get(i)));
      }
      
      }
      if (tr.left() != null) {
          t.addChild(CopyTree(tr.left()));
      }
      
      return t;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-03
        • 2018-03-16
        • 2011-12-27
        • 1970-01-01
        • 1970-01-01
        • 2016-07-19
        • 1970-01-01
        • 2020-02-15
        相关资源
        最近更新 更多