1. 程式人生 > >【二叉樹上的路徑數】及【過樹上兩個節點最長路徑】

【二叉樹上的路徑數】及【過樹上兩個節點最長路徑】

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+20;
vector<int>G[maxn]; 
int x,y,ans,n;
int dfs(int v){
	int res=0;
	//for(auto &i:G[v]) i 遍歷後面容器中的每個元素 
	for(int j=0;j<G[v].size();j++){
		int &i=G[v][j];
		res+=dfs(i);
	}
	ans+=res;
	return res+1;
}
int main(){
	while(scanf("%d",&n)!=EOF){
		for(int i=1;i<n;i++){
			scanf("%d%d",&x,&y);
			G[x].push_back(y);
		}
		ans=0;
		dfs(1);
		cout<<ans<<endl;
	}
	return 0;
}