找到n-ary树的最大值

时间:2012-11-02 06:53:00

标签: java algorithm recursion tree

我有一个n-ary树,由

的短NTN类定义
public class NTN P {
     public int value;
     public Set<NTN> children;
 }

我想找到这种n-ary树的最大值。让我们说它是一个简单的整数n-ary树,其值为:[parent:1 children:2,3,4] [parent:2 children:5,6] [parent:4 children 7,8,9]最大值只是9.我不知道如何开始编写一个方法来找到原型的最大值:

public static int maximum(NTN t);

从我尝试过:

public static int maximum(NTN t) {
  int max = 0;
      for (NTN e : t.children) {
          if (e.value > max)
              max = e.value;
      }

  return max;
}

上面的代码最多会返回4,这意味着它只检查t的子节点而不是后续的子节点集。在这种情况下,它不会检查子集4,[7,8,9]和2,[5,6]。如何更改它以便方法找到所有后续子节点的最大值?

5 个答案:

答案 0 :(得分:2)

public static int maximum(NTN t) {
  int max = t.value;
  Set<NTN> children = t.children;

  // only check if this node is not a leaf
  if (children != null && !children.isEmpty) {
    for (NTN e : children) {
      // here is the recursion
      int maxNext = maximum(e);

      if (maxNext > max) max = maxNext;
    }
  }

  return max;
}

希望这有助于:)

答案 1 :(得分:1)

你的解决方案不是Recursive,所以它不会继续你的子孩子,如果有的话。您可能需要查看Tabu Search。一种更简单的方法(但容易陷入local maximum)将是Hill Climbing

答案 2 :(得分:0)

我想像这样的东西会有所帮助,你就像树上的DFS一样遍历所有节点,你看每个节点的值,如果它大于你保持的静态变量的最大值你是公共类(例如public static int max),你将max设置为该节点的值,就像这样做(希望没有经过测试,注意返回类型是无效的,你直接更新你公共内部的变量)课程):

     public void maximum(NTN T){
            if (!T.children.isEmpty() && T.children != null){
                for(NTN e: T.children)
                    maximum(e)
            }
            if (PUBLIC_CLASS.MAX < T.value)
                PUBLIC_CLASS.MAX = T.value;
        }

答案 3 :(得分:0)

public static int maximum(NTN t) {
    int max = t.value;
    Set<NTN> children = t.children;
    if (children != null && !children.isEmpty) {
        for (NTN e : children) {
            max = Math.max(max, maximum(e));
        }
    }
}

答案 4 :(得分:0)

以下代码从一棵树中重新启动具有maxm值的完整节点

//以下是给定的Tree节点结构。

  

模板

class TreeNode
 {
    public:
        T data;
        vector<TreeNode<T>*> children;

        TreeNode(T data) {
            this->data = data;
        }

        ~TreeNode() {
            for (int i = 0; i < children.size(); i++) {
                delete children[i];
            }
        }
 };



TreeNode<int>* maxDataNode(TreeNode<int>* root) {

    if(root == NULL) return NULL;
    TreeNode<int>* maxNode = new TreeNode<int>(0);
    int max = 0;

    for(int i=0; i<root->children.size();i++){
        if(maxDataNode(root->children[i])->data > max)
        {    
            max = maxDataNode(root->children[i])->data;
            maxNode = maxDataNode(root->children[i]);
        }
    }
    if(root->data > maxNode->data)
    {
        maxNode = root;
        return maxNode;
    }
    return maxNode;

}
相关问题