#include <iostream> #include <vector> //结点的数据结构 struct Node { int _data; int _weight; Node* _left; Node* _right; Node(const int& x = 0,int weight=0) :_left(NULL) , _right(NULL) , _data(x) , _weight(weight) {} }; //建树 Node* CreateTree(const int* array,const int* weight,size_t size,int& i)//i=0 { /*if (array == NULL || weight==NULL || size == 0) return NULL;*/ if (array[i] == ‘#‘) return NULL; Node* root = new Node(array[i],weight[i]); root->_left = CreateTree(array,weight,size,++i); root->_right = CreateTree(array, weight, size, ++i); return root; } //先序遍历,把节点放到容器v中,结点对应的深度放到vdepth中(根结点的深度为0) Node* pushData(Node* root, int& max, int& min, std::vector<Node*>& v, std::vector<int>& vdepth,int depth) { Node* cur = root; if (cur){ v.push_back(cur); vdepth.push_back(depth); } while (cur){ pushData(cur->_left, max, min, v, vdepth, ++depth); if (cur->_left != NULL){ v.push_back(cur); vdepth.push_back(--depth); } else --depth; pushData(cur->_right, max, min, v, vdepth, ++depth); if (cur->_right != NULL){ v.push_back(cur); vdepth.push_back(--depth); } else{ --depth; if (cur->_weight > max) max = cur->_weight; if (cur->_weight < min) min = cur->_weight; } return cur; } return NULL; } int bigAndsmallWeightDistance(Node* root, int& max, int& min, std::vector<Node*>& v, std::vector<int>& vdepth, int depth) { pushData(root, max, min, v, vdepth, depth); int maxindex, minindex; //找到权值最大和最小的叶结点在v中对应的下标 for (int i = 0; i < v.size(); ++i){ if (v[i]->_weight == max){ maxindex = i; } if (v[i]->_weight == min){ minindex = i; } } int i, j; if (maxindex > minindex){ i = minindex; j = maxindex; } int retminindex = i; for (i; i <= j; ++i){ if (vdepth[i] < retminindex){ retminindex = vdepth[i];//retminindex下标所对应的v中结点即为所找叶子结点的公共父节点 } } //至此,就找到了这两个权值最大和最小的叶节点和它们的公共祖先节点的下标 return vdepth[maxindex] + vdepth[minindex] - 2 * vdepth[retminindex]; } int main() { /*int array[] = { 1, 2, 3, ‘#‘, ‘#‘, 4, 5, ‘#‘, ‘#‘, 6, ‘#‘, ‘#‘, 7, ‘#‘, 8, ‘#‘, ‘#‘ }; int weight[] = { 4, 2, 1, ‘#‘, ‘#‘, 5, 7, ‘#‘, ‘#‘, 8, ‘#‘, ‘#‘, 6, ‘#‘, 3, ‘#‘, ‘#‘, };*/ int array[] = { 1, 2, 3, 11, ‘#‘, 12, ‘#‘, ‘#‘, ‘#‘, 4, 5, ‘#‘, ‘#‘, 6, 9, ‘#‘, 10, ‘#‘, ‘#‘, ‘#‘, 7, ‘#‘, 8, ‘#‘, ‘#‘ }; int weight[] = { 4, 2, 2, 13, ‘#‘, 1, ‘#‘, ‘#‘, ‘#‘, 5, 7, ‘#‘, ‘#‘, 8, 9, ‘#‘, 10, ‘#‘, ‘#‘, ‘#‘,6, ‘#‘, 3, ‘#‘, ‘#‘, }; int i = 0; Node* root = CreateTree(array,weight,sizeof(array)/sizeof(array[0]),i); std::vector<Node*> v; std::vector<int> vdepth; int depth = 0; int maxweight=-1; int minweight = 100; int distance = bigAndsmallWeightDistance(root, maxweight, minweight, v, vdepth, depth); std::cout << distance << std::endl; system("pause"); }
时间: 2024-10-27 19:55:36