微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

基于输入模式的结构和计算树高

如何解决基于输入模式的结构和计算树高

假设我有此输入

5

4 -1 4 1 1

说明: 第一行包含节点?的数量。第二行包含?个整数 从−1到?− 1-节点的父代。如果它们中的第(个(0≤?≤?− 1)为-1,则节点?为根, 否则,它是第?个节点的父节点的从0开始的索引。

0 1 2 3 4

4 -1 4 1 1

现在我们可以看到节点号1是根,因为在第二行中-1对应于它。 另外,我们知道3号和4号节点是根节点1的子节点。此外,我们知道 节点0和2是节点4的子节点。

我必须获取这些数据并构造一棵树。基于该输入。但是,我得到了一个建议,我仍然无法理解。

“建议:利用以下事实:每棵树的标签 node是范围为0..?-1的整数:您可以将每个节点存储在 索引为节点标签的数组。通过将节点存储在 数组,您可以在任何具有其标签的节点上访问(1)。

分配?????[?]

对于?←0到?− 1:

?????[?] =新????

然后,读取每个父索引:

对于?ℎ???_?????←0到?− 1:

阅读??????_?????

如果??????_?????== -1:

????←?ℎ???_?????

其他:

?????[??????_?????].????ℎ???(?????[?ℎ???_?????])“

我尝试执行以下操作:

设置一个哈希表。关键是父母。及其子元素在数组列表中。因为生病总是在追加。目的是计算这棵树的高度。 在我的哈希图中,我将所有父级都作为键,并且树中的所有子级都是以ArrayList表示的值。树可能不是二叉树,因此我的节点可能有两个以上的子节点。如果此实现是一棵树!为什么。为什么它是一棵树,以及如何命名树,因为您没有Node类,并且根与任何其他父类一样。如果是一棵树。我什至如何计算它的高度?

void setUpTree() {
        tree = new HashMap<>(n);
        int num;
        for (int i = 0; i < n; i++) {
            num = parent[i];
            if (num == -1)
                tree.put(i,new ArrayList<>());
            else {
                tree.computeIfAbsent(num,k -> new ArrayList<>());
                tree.get(num).add(i);
            }
        }
    }

由于树是使用Array实现的,因此任务本身对我来说是难以理解的。我根据我的理解实现了setUpTree方法 我不知道我是否走对了。如果是这样。如何甚至计算高度。我将不胜感激任何解释或提示。 谢谢。

上下文的完整入门代码

public class tree_height {

static class FastScanner {
    StringTokenizer tok = new StringTokenizer("");
    BufferedReader in;

    FastScanner() {
        in = new BufferedReader(new InputStreamReader(system.in));
    }

    String next() throws IOException {
        while (!tok.hasMoreElements())
            tok = new StringTokenizer(in.readLine());
        return tok.nextToken();
    }

    int nextInt() throws IOException {
        return Integer.parseInt(next());
    }
}

public static class TreeHeight {
    int n;
    int[] parent;
    HashMap<Integer,ArrayList<Integer>> tree;

    void read() throws IOException {
        FastScanner in = new FastScanner();
        n = in.nextInt();
        parent = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = in.nextInt();
        }
    }

   //the implementation of the algorithm provided in the suggestion
    void setUpTree() {
        tree = new HashMap<>(n);
        int num;
        for (int i = 0; i < n; i++) {
            num = parent[i];
            if (num == -1)
                tree.put(i,k -> new ArrayList<>());
                tree.get(num).add(i);
            }
        }
    }

    int computeHeight() {
        //set up the tree to compute its height
        setUpTree();

        //Compute tree height here
}

static public void main(String[] args) throws IOException {
    new Thread(null,new Runnable() {
        public void run() {
            try {
                new tree_height().run();
            } catch (IOException ignored) {
            }
        }
    },"1",1 << 26).start();
}

public void run() throws IOException {
    TreeHeight tree = new TreeHeight();
    tree.read();
    System.out.println(tree.computeHeight());
}

解决方法

您可以从setUpTree()中删除computeHeight()函数,因为您没有在该函数中使用tree HashMap。

让我们尝试计算时间复杂度

考虑以下树:

enter image description here

我们正在计算每个节点的深度,并且为了计算节点的深度,我们进行迭代直到到达顶部。所以

0 we iterate over other nodes {}
1 we iterate over other nodes {0}
2 we iterate over other nodes {1,0}
3 we iterate over other nodes {2,1,0}

该算法的总体时间复杂度为O(n ^ 2)

我们正在做一些重复的工作吗?

是的,在第三次迭代中,我们知道2的深度,当我们为3做时,我们可以使用2的深度。一般来说,我们可以说

    depth[node] = 1 + depth[node->parent]

让我们用它来更新我们的算法

算法

      a. Create an auxilary array depth where we store depth of the nodes
      b. Iterate over each node:
          i.  If the depth of parent of node is known then 
              update depth[node]=1+depth[node -> parent] 
          ii. If the depth[node->parent] is not known,then 
              recursively calculate the depth and also update 
              the depth of each node in the path
      c. Height of the tree is the maximum depth among all the nodes

由于我们仅触摸每个节点一次,所以该算法的复杂度将为O(n)。

修改

为什么。为什么是一棵树,又怎么命名树,因为你没有 Node类,其根与任何其他父类一样。如果它是一个 树。

可以通过多种方式实现树数据结构,相似性node是树的概念,我们可以通过多种方式实现。一种方法是拥有一个Node

public class Node {
   int value;
   List<Node> childrens;
}

在您的情况下,我们没有明确创建一个Node类,但是哈希映射条目的值看起来与此Node类相似。映射中的每个键都代表一个节点及其子节点的值列表。因此,我想说的是,有多种方法可以实现一棵树,而您就是其中的一种。您的哈希图实现是adjacency list。在该问题中,仅使用数组来表示树。

如何计算高度 引用

可以使用此递归来计算树的高度

        heigh[node] = 1 + max( height[node->children])

让我们看看如何使用哈希图表示法将其写到给定的树上

算法

 int  height(HashMap map,int nodeId)
   if(map.get(nodeId).size() == 0)
      // Its the leaf
      return 0;
   int maxHeightsOfSubTress = 0;
   for i = 0 to map.get(nodeId).size()-1
      maxHeightsOfSubTress = max(maxHeightsOfSubTress,height(map,map.get(nodeId).get(i))
   return 1 + maxHeightsOfSubTress

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。