原文:

给定一棵树,其 n 节点从 1 到t5】nn–1和数组colors[]其中 colors[i]表示ith节点的颜色。任务是找到一个节点,使得连接到该节点的每个相邻树都由相同颜色的节点组成。如果不存在这样的节点,则打印-1。****

**输入: n = 8,颜色[] = {1,1,1,1,2,1,3}边= {(1,2) (1,3) (2,4) (2,7) (3,5) (3,6) (6,8)}****

****

想象这棵树****

**输出: 6 说明: 考虑节点 6,它有 2 棵树与之相连。其中一个扎根于 3,另一个扎根于 8。显然,以 3 为根的树有相同颜色的节点,以 8 为根的树只有一个节点。因此,节点 6 就是这样一个节点。****

**输入: n = 4,颜色[] = {1,2,3,4},边= {(1,3) (1,2 ) (2,4)} 输出: -1 说明: 没有这样的节点。****

**方法:思路是检查所有节点是否都有同色,那么任意一个节点都可以是根。否则,选择任意两个相邻且颜色不同的节点,并通过执行 dfs 检查这些节点的子树。如果这些节点中的任何一个满足条件,那么该节点可以是根。如果这两个节点都不满足条件,则不存在这样的根,并打印-1。****

  1. *遍历树,找到彼此相邻的前两个不同颜色的节点,比如说 *root1root2 。如果没有找到这样的节点,那么所有的节点都是相同的颜色,任何节点都可以作为。****
  2. *通过将 *root1 视为树的根,检查每个子树的所有节点的颜色是否相同。如果条件满足,那么根 1 就是答案。****
  3. *如果*根 1 不满足条件,对根 2 重复步骤 2。****
  4. *如果*根 2 不满足条件,则不存在这样的根,输出为-1。****

*下面是上述方法的实现:*

*c *

**// c   program for the above approach
#include 
using namespace std;
const int nn = 1e5   5;
// vector to store the tree
vector g[nn];
// function to perform dfs
void dfs(int node, int parent,
         bool& check,
         int current_colour,
         int* colours)
{
    // check is assigned to false if either it
    // is already false or the current_colour
    // is not same as the node colour
    check = check
            && (colours[node] == current_colour);
    // iterate over the neighbours of node
    for (auto a : g[node]) {
        // if the neighbour is
        // not the parent node
        if (a != parent) {
            // call the function
            // for the neighbour
            dfs(a, node, check,
                current_colour,
                colours);
        }
    }
}
// function to check whether all the
// nodes in each subtree of the given
// node have same colour
bool checkpossibility(
    int root, int* colours)
{
    // initialise the boolean answer
    bool ans = true;
    // iterate over the neighbours
    // of selected root
    for (auto a : g[root]) {
        // initialise the colour
        // for this subtree
        // as the colour of
        // first neighbour
        int current_colour = colours[a];
        // variable to check
        // condition of same
        // colour for each subtree
        bool check = true;
        // dfs function call
        dfs(a, root, check,
            current_colour, colours);
        // check if any one subtree
        // does not have all
        // nodes of same colour
        // then ans will become false
        ans = ans && check;
    }
    // return the answer
    return ans;
}
// function to add edges to the tree
void addedge(int x, int y)
{
    // y is added as a neighbour of x
    g[x].push_back(y);
    // x is added as a neighbour of y
    g[y].push_back(x);
}
// function to find the node
void solve(int* colours, int n)
{
    // initialise root1 as -1
    int root1 = -1;
    // initialise root2 as -1
    int root2 = -1;
    // find the first two nodes of
    // different colour which are adjacent
    // to each other
    for (int i = 1; i <= n; i  ) {
        for (auto a : g[i]) {
            if (colours[a] != colours[i]) {
                root1 = a;
                root2 = i;
                break;
            }
        }
    }
    // if no two nodes of different
    // colour are found
    if (root1 == -1) {
        // make any node (say 1)
        // as the root
        cout << endl
             << "1" << endl;
    }
    // check if making root1
    // as the root of the
    // tree solves the purpose
    else if (
        checkpossibility(root1, colours)) {
        cout << root1 << endl;
    }
    // check  for root2
    else if (
        checkpossibility(root2, colours)) {
        cout << root2 << endl;
    }
    // otherwise no such root exist
    else {
        cout << "-1" << endl;
    }
}
// driver code
int32_t main()
{
    // number of nodes
    int n = 8;
    // add edges
    addedge(1, 2);
    addedge(1, 3);
    addedge(2, 4);
    addedge(2, 7);
    addedge(3, 5);
    addedge(3, 6);
    addedge(6, 8);
    // node colours
    // 0th node is extra to make
    // the array 1 indexed
    int colours[9] = { 0, 1, 1, 1,
                       1, 1, 2, 1, 3 };
    solve(colours, n);
    return 0;
}**

*java 语言(一种计算机语言,尤用于创建网站)*

**// java program for the above approach
import java.util.*;
class gfg{
static int nn = (int)(1e5   5);
// vector to store the tree
@suppresswarnings("unchecked")
static vector []g = new vector[nn];
// function to perform dfs
static void dfs(int node, int parent,
                boolean check,
                int current_colour,
                int[] colours)
{
    // check is assigned to false if either it
    // is already false or the current_colour
    // is not same as the node colour
    check = check &&
           (colours[node] == current_colour);
    // iterate over the neighbours of node
    for(int a : g[node])
    {
        // if the neighbour is
        // not the parent node
        if (a != parent)
        {
            // call the function
            // for the neighbour
            dfs(a, node, check,
                current_colour,
                colours);
        }
    }
}
// function to check whether all the
// nodes in each subtree of the given
// node have same colour
static boolean checkpossibility(int root,
                                int[] colours)
{
    // initialise the boolean answer
    boolean ans = true;
    // iterate over the neighbours
    // of selected root
    for(int a : g[root])
    {
        // initialise the colour
        // for this subtree
        // as the colour of
        // first neighbour
        int current_colour = colours[a];
        // variable to check
        // condition of same
        // colour for each subtree
        boolean check = true;
        // dfs function call
        dfs(a, root, check,
            current_colour, colours);
        // check if any one subtree
        // does not have all
        // nodes of same colour
        // then ans will become false
        ans = ans && check;
    }
    // return the answer
    return ans;
}
// function to add edges to the tree
static void addedge(int x, int y)
{
    // y is added as a neighbour of x
    g[x].add(y);
    // x is added as a neighbour of y
    g[y].add(x);
}
// function to find the node
static void solve(int[] colours, int n)
{
    // initialise root1 as -1
    int root1 = -1;
    // initialise root2 as -1
    int root2 = -1;
    // find the first two nodes of
    // different colour which are adjacent
    // to each other
    for(int i = 1; i <= n; i  )
    {
        for(int a : g[i])
        {
            if (colours[a] != colours[i])
            {
                root1 = a;
                root2 = i;
                break;
            }
        }
    }
    // if no two nodes of different
    // colour are found
    if (root1 == -1)
    {
        // make any node (say 1)
        // as the root
        system.out.println("1"   "\n");
    }
    // check if making root1
    // as the root of the
    // tree solves the purpose
    else if (checkpossibility(root1, colours))
    {
        system.out.print(root1   "\n");
    }
    // check for root2
    else if (checkpossibility(root2, colours))
    {
        system.out.print(root2   "\n");
    }
    // otherwise no such root exist
    else
    {
        system.out.print("-1"   "\n");
    }
}
// driver code
public static void main(string[] args)
{
    // number of nodes
    int n = 8;
    for(int i = 0; i < g.length; i  )
        g[i] = new vector();
    // add edges
    addedge(1, 2);
    addedge(1, 3);
    addedge(2, 4);
    addedge(2, 7);
    addedge(3, 5);
    addedge(3, 6);
    addedge(6, 8);
    // node colours 0th node is extra
    // to make the array 1 indexed
    int colours[] = { 0, 1, 1, 1,
                      1, 1, 2, 1, 3 };
    solve(colours, n);
}
}
// this code is contributed by 29ajaykumar**

*python 3*

**# python3 program for the above approach
nn = 1e5   5
# vector to store tree
g = []
for i in range(int(nn)):
    g.append([])
# function to perform dfs
def dfs(node, parent, check,
        current_colour, colours):
    # check is assigned to false if 
    # either it is already false or
    # the current_colour is not same
    # as the node colour
    check[0] = check[0] & (colours[node] ==
                           current_colour)
    # iterate over the neighbours of node
    for a in g[node]:
        # if the neighbour is
        # not the parent node
        if a != parent:
            # call the function
            # for the neighbour
            dfs(a, node, check,
                current_colour, colours)
# function to check whether all the
# nodes in each subtree of the given
# node have same colour
def checkpossibility(root, colours):
    # initialise the boolean answer
    ans = true
    for a in g[root]:
        # initialise the colour
        # for this subtree
        # as the colour of
        # first neighbour
        current_colour = colours[a]
        # variable to check
        # condition of same
        # colour for each subtree
        check = [true]
        # dfs function call
        dfs(a, root, check,
            current_colour, colours)
        # check if any one subtree
        # does not have all
        # nodes of same colour
        # then ans will become false
        ans = ans & check[0]
    # return the ans
    return ans
# function to add edges to the tree
def addedge(x, y):
    # y is added as a neighbour of x
    g[x].append(y)
    # x is added as a neighbour of y
    g[y].append(x)
# function to find the node
def solve(colours, n):
    # initialise the root1 as -1
    root1 = -1
    # initialise the root 2 as -1
    root2 = -1
    # find the first two nodes of
    # different colour which are adjacent
    # to each other
    for i in range(1, n   1):
        for a in g[i]:
            if colours[a] != colours[i]:
                root1 = a
                root2 = i
                break
    # if no two nodes of different
    # colour are found
    if root1 == -1:
        # make any node (say 1)
        # as the root
        print(1)
    # check if making root1
    # as the root of the
    # tree solves the purpose
    elif checkpossibility(root1, colours):
        print(root1)
    # check for root2
    elif checkpossibility(root2, colours):
        print(root2)
    # otherwise no such root exist
    else:
        print(-1)
# driver code
# number of nodes
n = 8
# add edges
addedge(1, 2)
addedge(1, 3)
addedge(2, 4)
addedge(2, 7)
addedge(3, 5)
addedge(3, 6)
addedge(6, 8)
# node colours
# 0th node is extra to make
# the array 1 indexed
colours = [ 0, 1, 1, 1, 1,
            1, 2, 1, 3 ]
solve(colours, n)
# this code is contributed by stuti pathak**

*c#*

**// c# program for the above approach
using system;
using system.collections.generic;
class gfg{
    static int nn = (int)(1e5   5);
    // list to store the tree
    static list[] g = new list[ nn ];
    // function to perform dfs
    static void dfs(int node, int parent, bool check,
                    int current_colour, int[] colours)
    {
        // check is assigned to false if either it
        // is already false or the current_colour
        // is not same as the node colour
        check = check && (colours[node] == current_colour);
        // iterate over the neighbours of node
        foreach(int a in g[node])
        {
            // if the neighbour is
            // not the parent node
            if (a != parent)
            {
                // call the function
                // for the neighbour
                dfs(a, node, check,
                    current_colour, colours);
            }
        }
    }
    // function to check whether all the
    // nodes in each subtree of the given
    // node have same colour
    static bool checkpossibility(int root, int[] colours)
    {
        // initialise the bool answer
        bool ans = true;
        // iterate over the neighbours
        // of selected root
        foreach(int a in g[root])
        {
            // initialise the colour
            // for this subtree
            // as the colour of
            // first neighbour
            int current_colour = colours[a];
            // variable to check
            // condition of same
            // colour for each subtree
            bool check = true;
            // dfs function call
            dfs(a, root, check, current_colour, colours);
            // check if any one subtree
            // does not have all
            // nodes of same colour
            // then ans will become false
            ans = ans && check;
        }
        // return the answer
        return ans;
    }
    // function to add edges to the tree
    static void addedge(int x, int y)
    {
        // y is added as a neighbour of x
        g[x].add(y);
        // x is added as a neighbour of y
        g[y].add(x);
    }
    // function to find the node
    static void solve(int[] colours, int n)
    {
        // initialise root1 as -1
        int root1 = -1;
        // initialise root2 as -1
        int root2 = -1;
        // find the first two nodes of
        // different colour which are adjacent
        // to each other
        for (int i = 1; i <= n; i  )
        {
            foreach(int a in g[i])
            {
                if (colours[a] != colours[i])
                {
                    root1 = a;
                    root2 = i;
                    break;
                }
            }
        }
        // if no two nodes of different
        // colour are found
        if (root1 == -1)
        {
            // make any node (say 1)
            // as the root
            console.writeline("1"   "\n");
        }
        // check if making root1
        // as the root of the
        // tree solves the purpose
        else if (checkpossibility(root1, colours))
        {
            console.write(root1   "\n");
        }
        // check for root2
        else if (checkpossibility(root2, colours))
        {
            console.write(root2   "\n");
        }
        // otherwise no such root exist
        else
        {
            console.write("-1"   "\n");
        }
    }
    // driver code
    public static void main(string[] args)
    {
        // number of nodes
        int n = 8;
        for (int i = 0; i < g.length; i  )
            g[i] = new list();
        // add edges
        addedge(1, 2);
        addedge(1, 3);
        addedge(2, 4);
        addedge(2, 7);
        addedge(3, 5);
        addedge(3, 6);
        addedge(6, 8);
        // node colours 0th node is extra
        // to make the array 1 indexed
        int[] colours = {0, 1, 1, 1, 1, 1, 2, 1, 3};
        solve(colours, n);
    }
}
// this code is contributed by rajput-ji**

*java 描述语言*

****

**output: 

6****

*时间复杂度: o(n) 其中n 为树中节点数。辅助空间: o(1)***