# G家练习

**Water Drop & Leaves**

Water drop from root of a tree and each tree node contains several branches. It takes certain amount of time for water to drop from one node to another. Calculate the shortest time takes for water to cover all leaves.&#x20;

这题其实是求从Root到底最长的边，就是把值往下传，传到底求global max。

```
int max = Integer.MIN_VALUE;
public int LongestPathFromRootToEnd(TreeNode root) {
    if (root == null) return 0;
    helper(root, 0);
    return max;
}

private void helper(TreeNode root, int curtVal) {
    if (root.children.length == 0)  {
        max = Math.max(max, curtVal);
        return;
    }
    for (int i = 0; i < root.children.length; i++) {
        if (root.children[i] != null) {
            helper(root.children[i], curtVal + root.edgeVal[i]);
        }
    }
}
```

Follow-Up 2: What if it is a graph instead of a tree? One TreeNode can link to another one in many ways:

![Follow-up](https://249794273-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Laur3QE_YAExtEZegFt%2F-LgyKH65OncgsYK4XkkM%2F-LgyLGSWRjcByQeKBkrx%2Fimage.png?alt=media\&token=020cb8bf-bc54-446b-b663-504a25faac00)

单方向图找最长边，用Toplogical Sort。先把所有的点通过toplogical order走一遍，每个点包含一个Integer.MIN\_VALUE的值，然后更新为root到这个点的最长边的值。

{% embed url="https://www.geeksforgeeks.org/find-longest-path-directed-acyclic-graph/" %}



#### Rooms and Keys

![](https://lh5.googleusercontent.com/WZ7nvOoyf2QTyS5GkWh3_Eiu5GpcJBLGOKOJAhJVUgbY7W2YSYo61zR3xoL9lzyV0baAwZNRl1QlYqzzulHvbnoLhhUsFJTE2QjrfSWCIA1EQZbKnFMNvfx8yQZmrNzxNgHMVW7Z)

#### Build City on a Highway

