Mapping a Tree to a HashTable data structure

I think a HashTable (of a HashSet) is a very convenient way to represent a tree. It gives you instant access to any element of the tree if there is a unique id representing each node. The problem (and code) below exemplifies this point. Once the representation is there, performing a Depth-First Search becomes very trivial. Code is down below, cheers, ACC.

Kill Process - LeetCode

You have n processes forming a rooted tree structure. You are given two integer arrays pid and ppid, where pid[i] is the ID of the ith process and ppid[i] is the ID of the ith process's parent process.

Each process has only one parent process but may have multiple children processes. Only one process has ppid[i] = 0, which means this process has no parent process (the root of the tree).

When a process is killed, all of its children processes will also be killed.

Given an integer kill representing the ID of a process you want to kill, return a list of the IDs of the processes that will be killed. You may return the answer in any order.

 

Example 1:

Input: pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5
Output: [5,10]
Explanation: The processes colored in red are the processes that should be killed.

Example 2:

Input: pid = [1], ppid = [0], kill = 1
Output: [1]

 

Constraints:

  • n == pid.length
  • n == ppid.length
  • 1 <= n <= 5 * 104
  • 1 <= pid[i] <= 5 * 104
  • 0 <= ppid[i] <= 5 * 104
  • Only one process has no parent.
  • All the values of pid are unique.
  • kill is guaranteed to be in pid.

public class Solution {
    public IList KillProcess(IList pid, IList ppid, int kill)
    {
        Hashtable tree = new Hashtable();

        for (int i = 0; i < ppid.Count; i++)
        {
            int parent = ppid[i];
            int child = pid[i];

            if (!tree.ContainsKey(parent)) tree.Add(parent, new HashSet());
            HashSet children = (HashSet)tree[parent];
            children.Add(child);
        }

        IList retVal = new List();
        retVal.Add(kill);
        _KillProcess(tree, kill, retVal);

        return retVal;
    }

    private void _KillProcess(Hashtable tree, int kill, IList retVal)
    {
        if (!tree.ContainsKey(kill)) return;

        HashSet children = (HashSet)tree[kill];
        foreach (int child in children)
        {
            retVal.Add(child);
            _KillProcess(tree, child, retVal);
        }
    }
}

Comments

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Classic Dynamic Programming IX

HashSet I