problemscpp
A collection of my answers to algorithm problems in c++.
静态 Public 成员函数 | 所有成员列表
leetcode::minimum_height_trees::Solution类 参考

#include <leetcode.h>

静态 Public 成员函数

static int findLongestNode (int u, vector< int > &parent, vector< vector< int > > &adj)
 
static vector< int > findMinHeightTrees (int n, vector< vector< int > > &edges)
 

详细描述

在文件 leetcode.h2125 行定义.

成员函数说明

◆ findLongestNode()

int leetcode::minimum_height_trees::Solution::findLongestNode ( int  u,
vector< int > &  parent,
vector< vector< int > > &  adj 
)
static

在文件 leetcode.cpp5765 行定义.

5765 {
5766 const int n = adj.size();
5767 queue<int> qu;
5768 vector<bool> visit(n);
5769 qu.emplace(u);
5770 visit[u] = true;
5771 int node = -1;
5772
5773 while(!qu.empty()) {
5774 const int curr = qu.front();
5775 qu.pop();
5776 node = curr;
5777 for(auto &v: adj[curr]) {
5778 if(!visit[v]) {
5779 visit[v] = true;
5780 parent[v] = curr;
5781 qu.emplace(v);
5782 }
5783 }
5784 }
5785 return node;
5786 }

被这些函数引用 findMinHeightTrees().

◆ findMinHeightTrees()

vector< int > leetcode::minimum_height_trees::Solution::findMinHeightTrees ( int  n,
vector< vector< int > > &  edges 
)
static

在文件 leetcode.cpp5736 行定义.

5736 {
5737 if(n == 1) {
5738 return {0};
5739 }
5740 vector<vector<int>> adj(n);
5741 for(auto &edge: edges) {
5742 adj[edge[0]].emplace_back(edge[1]);
5743 adj[edge[1]].emplace_back(edge[0]);
5744 }
5745
5746 vector parent(n, -1);
5747 /* 找到与节点 0 最远的节点 x */
5748 const int x = findLongestNode(0, parent, adj);
5749 /* 找到与节点 x 最远的节点 y */
5750 int y = findLongestNode(x, parent, adj);
5751 /* 求出节点 x 到节点 y 的路径 */
5752 vector<int> path;
5753 parent[x] = -1;
5754 while(y != -1) {
5755 path.emplace_back(y);
5756 y = parent[y];
5757 }
5758 const int m = path.size();
5759 if(m % 2 == 0) {
5760 return {path[m / 2 - 1], path[m / 2]};
5761 }
5762 return {path[m / 2]};
5763 }
static int findLongestNode(int u, vector< int > &parent, vector< vector< int > > &adj)
Definition: leetcode.cpp:5765

引用了 findLongestNode().


该类的文档由以下文件生成: