int GetMaxDistance(TreeNode* root,int& maxLeft,int& maxRight) { if(root == NULL) { maxLeft = 0; maxRight = 0; return 0; } int maxLL,maxLR,maxRL,maxRR; int maxDistLeft,maxDistRight; if(root->left != NULL) { maxDistLeft = GetMaxDistance(root->left,maxLL,maxLR); maxLeft = std::max(maxLL,maxLR) + 1; } else { maxDistLeft = 0; maxLeft = 0; } if(root->right != NULL) { maxDistRight = GetMaxDistance(root->right,maxRL,maxRR); maxRight= std::max(maxRL,maxRR) + 1; } else { maxDistRight = 0; maxRight = 0; } return std::max(std::max(maxDistLeft,maxDistRight),maxLeft+maxRight); }
void Test4(){ //情况1:最长路径就在根节点所在的树中 int arr1[] = {1,2,3,4,0,0,0,5,0,0,6,7,0,8,0,0,9}; //情况2:最长路径在根节点所在的子树中 int arr2[] = {1,2,3,4,0,0,5,0,6}; Node_p root1 = CreateBinaryTree(arr1,sizeof(arr1)/sizeof(*arr1),0); Node_p root2 = CreateBinaryTree(arr2,sizeof(arr2)/sizeof(*arr2),0); cout<<GetMaxDistance(root1)<<endl; //6 cout<<GetMaxDistance(root2)<<endl; //4 PrevOrder(root1); InOrder(root1); PostOrder(root1); GetTreeMirror(root1); cout<<endl; PrevOrder(root1); InOrder(root1); PostOrder(root1); cout<<endl; PrevOrder(root2); InOrder(root2); PostOrder(root2); GetTreeMirror(root2); cout<<endl; PrevOrder(root2); InOrder(root2); PostOrder(root2); }
float Source::GetMaxDistance() const { #ifdef HAS_AUDIO_SOURCE return impl->GetMaxDistance(); #else throw System::PunkException(L"Audio source is not available"); #endif }
/** *@ classify unclassification sample */ string CTest_Knn::Classify(struct dataVector Sample,int k) { double dist=0; int maxid=0,i,tmpfreq=1; //freq[k] store the number of each class apperaed in k-nearest nighbour vector<int> freq; distanceStruct gND; string curClassLable = " "; //memset(&freq,1,sizeof(freq)); //initialized freq[k] to 1 for(i=0; i<k; ++i) { freq.push_back(1); } //step.1---initalize the distance to MAX_VALUE for(i=0;i<k;i++) { gND.distance = MAX_VALUE; gNearestDistance.push_back(gND); } //step.2---calculate K-nearest neighbour distance for(i=0;i<curTrainingSetSize;i++) { //step.2.1---calculate the distance between unclassification sample and each training sample dist=euclideanDistance(gTrainingSet[i],Sample); //step.2.2---get the max distance in gNearestDistance maxid=GetMaxDistance(k); //step.2.3---if the dist less than the maxdistance in gNearestDistance£¬it will be one of k-nearest neighbour if(dist<gNearestDistance[maxid].distance) { gNearestDistance[maxid].ID=gTrainingSet[i].ID; gNearestDistance[maxid].distance=dist; gNearestDistance[maxid].classLabel=gTrainingSet[i].classLabel; } } //step.3---statistics the number of each class appeared for(i=0;i<k;i++) { for(int j=0;j<k;j++) { if((i!=j)&&(gNearestDistance[i].classLabel==gNearestDistance[j].classLabel)) { freq[i]+=1; } } } //step.4---chose the class label with maximum frequency for(i=0;i<k;i++) { if(freq[i]>tmpfreq) { tmpfreq=freq[i]; curClassLable=gNearestDistance[i].classLabel; } } return curClassLable; }