

Bucu yang tinggal ini adalah bucu yang membentuk simpul akar dengan ketinggian minimum. Kami melakukan ini secara berulang sehingga hanya 1 atau 2 bucu dibiarkan dihapuskan. Dalam pendekatan ini kita melakukan BFS / DFS melintasi dari simpul daun (simpul yang mempunyai darjah = 1), terus hapus daun, dan teruskan ke jirannya. Perlu difahami bahawa pokok hanya boleh dimiliki 1 atau 2 bucu yang membentuk simpul akar dengan ketinggian minimum. Kerumitan Masa: T (n) = O (V + E), tetapi untuk pokok E = V-1, oleh itu T (n) = O (2V - 1) = O (V).} Roots for minimum height tree are : 1 2 Analisis Kerumitan ("Roots for minimum height tree are : ") * par stores parent of each vertex during BFS traversalĪrrayList largestPath = new ArrayList() ĪrrayList result = rootMinHeight(adj,v) Static ArrayList rootMinHeight(ArrayList > adj,int v) Static int BFS(int s,ArrayList> adj,int v) * root for minimum height tree lie at mid of the diameter */ * obtain the vertex, that as a root form minimum height tree */ * main function to implement above function */ * result vector to store mid elements of theĭiameter, these elements are roots(or root) that form * begin traversal along the diameter starting * vector to store the diameter of the given tree */ This is used to track the path between first and last (diameter)*/ * par store parent of each vertex during BFS traversal Minimum height vertex/vertices lie at the centre * first and last form diameter of the tree and * find the vertex at largest distance from first

* take any vertex and find vertex at largest distance from it * function that return nodes that form root with minimum height */ * find vertex with largest distance from source */ * to store vertex that is at largest distance from source */
Contoh program queue dengan linked list update#
* update distance of neighbors from current node */ * mark neighbors of current largest as visited */ * define vectors to store visited status * function to perform BFS from a source vertexĪnd return vertex at largest distance from source */ * function to add edge between nodes u and v */ Pin Pin Pin Pin Pin Pelaksanaan Program C ++ #include

Pilih mana-mana bucu rawak (katakanlah bucu dengan nilai 0) dan cari bucu (katakanlah pertama ) yang berada pada jarak paling besar dari bucu yang dipilih.Sekiranya panjang diameternya sama rata, dua bucu tengah adalah akar ketinggian minimum dan jika panjangnya ganjil, satu-satunya bucu tengah adalah akar ketinggian minimum. Kami dapati diameter pokok, yang titik tengah diameter adalah akar ketinggian minimum. Melintasi berdasarkan BFS dari simpul daun.

Pinīucu 2 dan 1 dapat membentuk akar dengan tinggi pokok minimum. Bucu 1 dan 2 dapat membentuk akar dengan tinggi pokok minimum.īucu 4 boleh membentuk akar dengan pokok ketinggian minimum.
