列表

详情


1506. 找到 N 叉树的根节点

给定一棵 N 叉树 的所有节点在一个数组  Node[] tree 中,树中每个节点都有 唯一的值

找到并返回 N 叉树的 根节点

 

自定义测试:

N 叉树的输入序列为其层序遍历序列,每组子节点用 null 分隔(见示例)。

上图中的 N 叉树的序列化描述为 [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]

测试将以下列方式进行:

 

示例 1:

输入:tree = [1,null,3,2,4,null,5,6]
输出:[1,null,3,2,4,null,5,6]
解释:来自输入数据的树如上所示。
驱动程序代码创建树,并以任意顺序向 findRoot 提供 Node 对象。
例如,传递的数组可以是 [Node(5),Node(4),Node(3),Node(6),Node(2),Node(1)] 或 [Node(2),Node(6),Node(1),Node(3),Node(5),Node(4)] 。
findRoot 函数应该返回根 Node(1) ,驱动程序代码将序列化它并与输入数据进行比较。
输入数据和序列化的 Node(1) 相同,因此测试通过。

示例 2:

输入:tree = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]

 

提示:

 

进阶:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: Node* findRoot(vector<Node*> tree) { } };

cpp 解法, 执行用时: 100 ms, 内存消耗: 249.8 MB, 提交时间: 2023-10-16 21:52:06

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    Node* findRoot(vector<Node*> tree) {
        //////// 看一个Node有没有父亲
        unordered_set<Node *> has_parent;
        for (auto x: tree)
            for (auto y: x->children)
                has_parent.insert(y);
        for (auto x: tree)
            if (has_parent.find(x) == has_parent.end())
                return x;
        
        return NULL;    //仅仅为了编译通过
    }
    
    Node* findRoot2(vector<Node*> tree) {
        //////// 看一个Node有没有入
        unordered_set<Node *> has_in;
        for (auto x: tree)
            for (auto y: x->children)
                has_in.insert(y);
        for (auto x: tree)
            if (has_in.find(x) == has_in.end())
                return x;
        
        return NULL;    //仅仅为了编译通过
    }
};

java 解法, 执行用时: 15 ms, 内存消耗: 47.8 MB, 提交时间: 2023-10-16 21:51:09

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    
    public Node() {
        children = new ArrayList<Node>();
    }
    
    public Node(int _val) {
        val = _val;
        children = new ArrayList<Node>();
    }
    
    public Node(int _val,ArrayList<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public Node findRoot(List<Node> tree) {
        HashSet<Node> set = new HashSet<Node>();
        for (Node node : tree) {
            for (Node child : node.children) {
                set.add(child);
            }
        }
        for (Node node : tree) {
            if (!set.contains(node)) {
                return node;
            }
        }
        return null;
    }
}

python3 解法, 执行用时: 120 ms, 内存消耗: 26.6 MB, 提交时间: 2023-10-16 21:50:37

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children if children is not None else []
"""
class Solution:
    def findRoot(self, tree: List['Node']) -> 'Node':
        #### 看有没有父亲
        has_parent = set()
        for x in tree:
            for y in x.children:
                has_parent.add(y)
        for x in tree:
            if x not in has_parent:
                return x
                
    def findRoot2(self, tree: List['Node']) -> 'Node':
        #### 看有没有入
        has_in = set()
        for x in tree:
            for y in x.children:
                has_in.add(y)
        for x in tree:
            if x not in has_in:
                return x
                
    def findRoot3(self, tree: List['Node']) -> 'Node':
        #### 异或
        xornum = 0
        for x in tree:
            xornum ^= x.val
            for y in x.children:
                xornum ^= y.val

        for x in tree:
            if x.val == xornum:
                return x
                
    def findRoot4(self, tree: List['Node']) -> 'Node':
        node_depth = defaultdict(int)   #结点--深度

        #### 求结点的深度
        def get_depth(x : 'Node') -> int:
            if x in node_depth:
                return node_depth[x]
            if len(x.children) == 0:
                node_depth[x] = 1
                return 1
            max_dep = max([get_depth(y) for y in x.children])
            node_depth[x] = max_dep + 1
            return max_dep + 1

        for x in tree:
            get_depth(x)

        #### 最大深度
        max_dep = -1
        res = None
        for node, dep in node_depth.items():
            if dep > max_dep:
                max_dep = dep
                res = node
        return res

golang 解法, 执行用时: 12 ms, 内存消耗: 9.5 MB, 提交时间: 2023-10-16 21:49:11

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */
func findRoot(tree []*Node) *Node {
    a := 0
	for _, node := range tree {
		a ^= node.Val
		for _, child := range node.Children {
			a ^= child.Val
		}
	}
	for _, node := range tree {
		if node.Val == a {
			return node
		}
	}
	return nil
}

func findRoot1(tree []*Node) *Node {
	m := make(map[*Node]int)
	for _, node := range tree {
		if _, exist := m[node]; !exist {
			m[node] = 0
		}
		for _, child := range node.Children {
			m[child]++
		}
	}
	for node, times := range m {
		if times == 0 {
			return node
		}
	}
	return nil
}

上一题