【題目描述】
Givennnodes labeled from0ton - 1and a list ofundirectededges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
【注】You can assume that no duplicate edges will appear in edges. Since all edges areundirected,[0, 1]is the same as[1, 0]and thus will not appear together in edges.
給出n個節點,標號分別從0到n - 1并且給出一個無向邊的列表 (給出每條邊的兩個頂點), 寫一個函數去判斷這張`無向`圖是否是一棵樹
【注】你可以假設我們不會給出重復的邊在邊的列表當中.無向邊[0, 1]和[1, 0]是同一條邊, 因此他們不會同時出現在我們給你的邊的列表當中。
【題目鏈接】
www.lintcode.com/en/problem/graph-valid-tree/
【題目解析】
初始化Union Find的father map,讓每一個節點的初始parent指向自己(自己跟自己是一個Group);在循環讀取edge list時,查找兩個節點的parent,如果相同,說明形成了環(Cycle),那么這便不符合樹(Tree)的定義,反之,如果不相同,則將其中一個節點設為另一個的parent,繼續循環。
此外還有需要注意的是對于vertex和edge的validation,|E| = |V| - 1,也就是要驗證edges.length == n,如果該條件不滿足,則Graph一定不是valid tree。
【參考答案】