1506. Find Root of N-Ary Tree

선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.

Вам given все узлы N-арного дерева в виде 배열а объектов Node, где каждый узел имеет уникальное значение.

return корень N-арного дерева.

예제:

Input: tree = [1,null,3,2,4,null,5,6]

Output: [1,null,3,2,4,null,5,6]

Explanation: The tree from the input data is shown above.

The driver code creates the tree and gives findRoot the Node objects in an arbitrary order.

For example, the passed array could be [Node(5),Node(4),Node(3),Node(6),Node(2),Node(1)] or [Node(2),Node(6),Node(1),Node(3),Node(5),Node(4)].

The findRoot function should return the root Node(1), and the driver code will serialize it and compare with the input data.

The input data and serialized Node(1) are the same, so the test passes.

C# 해법

매칭됨/원본
public class Solution {
    public Node FindRoot(IList<Node> tree) {
        HashSet<int> seen = new HashSet<int>();
        foreach (Node node in tree) {
            foreach (Node child in node.children) {
                seen.Add(child.val);
            }
        }
        Node root = null;
        foreach (Node node in tree) {
            if (!seen.Contains(node.val)) {
                root = node;
                break;
            }
        }
        return root;
    }
}

C++ 해법

자동 초안, 제출 전 검토
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public Node FindRoot(IList<Node> tree) {
        HashSet<int> seen = new HashSet<int>();
        foreach (Node node in tree) {
            foreach (Node child in node.children) {
                seen.push_back(child.val);
            }
        }
        Node root = null;
        foreach (Node node in tree) {
            if (!seen.Contains(node.val)) {
                root = node;
                break;
            }
        }
        return root;
    }
}

Java 해법

매칭됨/원본
class Solution {
    public Node findRoot(List<Node> tree) {
        HashSet<Integer> seen = new HashSet<Integer>();

        for (Node node : tree) {
            for (Node child : node.children) {
                seen.add(child.val);
            }
        }

        Node root = null;
        for (Node node : tree) {
            if (!seen.contains(node.val)) {
                root = node;
                break;
            }
        }
        return root;
    }
}

JavaScript 해법

매칭됨/원본
var findRoot = function(tree) {
    const seen = new Set();

    for (const node of tree) {
        for (const child of node.children) {
            seen.add(child.val);
        }
    }

    for (const node of tree) {
        if (!seen.has(node.val)) {
            return node;
        }
    }
};

Go 해법

매칭됨/원본
func findRoot(tree []*Node) *Node {
    seen := make(map[int]struct{})

    for _, node := range tree {
        for _, child := range node.Children {
            seen[child.Val] = struct{}{}
        }
    }

    for _, node := range tree {
        if _, found := seen[node.Val]; !found {
            return node
        }
    }

    return nil
}

Algorithm

Используйте хэшсет (named as seen) для отслеживания всех посещенных дочерних узлов. В конечном итоге корневой узел не будет в этом множестве.

Выполняйте первую итерацию, проходя по elementам 입력ного списка. Для каждого elementа добавляйте его дочерние узлы в хэшсет seen. Поскольку значение каждого узла уникально, можно добавлять либо сам узел, либо просто его значение в хэшсет.

Посетите список еще раз. На этот раз у нас будут все дочерние узлы в хэшсете. Как только вы наткнетесь на узел, который не находится в хэшсете, это и будет корневой узел, который мы ищем.

😎

Vacancies for this task

활성 채용 with overlapping task tags are 표시됨.

전체 채용
아직 활성 채용이 없습니다.