集团数据治理平台功能架构设计规划与落地实践
2026/9/6 15:34:43
建树有两种方式,深度优先和广度优先,代码如下
#include<iostream>#include<vector>#include<stack>#include<deque>usingnamespacestd;structBinaryTree{intdata;BinaryTree*left=nullptr;BinaryTree*right=nullptr;BinaryTree(intd):data(d){}};BinaryTree*buildDFS(vector<int>&input){structStackNode{BinaryTree*cur;size_t arrary_index;size_t process_flag=0;StackNode(BinaryTree*c,size_t a):cur(c),arrary_index(a){}};stack<StackNode>work_stack;BinaryTree*root=newBinaryTree(input[0]);work_stack.push(StackNode(root,1));while(work_stack.empty()==false){if(work_stack.top().process_flag==0){size_t temp=0;if((temp=2*work_stack.top().arrary_index)<=input.size()){work_stack.top().cur->left=newBinaryTree(input[temp-1]);work_stack.push(StackNode(work_stack.top().cur->left,temp));}else{work_stack.top().process_flag=2;}}elseif(work_stack.top().process_flag==1){size_t temp=0;if((temp=2*work_stack.top().arrary_index+1)<=input.size()){work_stack.top().cur->right=newBinaryTree(input[temp-1]);work_stack.push(StackNode(work_stack.top().cur->right,temp));}else{work_stack.top().process_flag=2;}}else{work_stack.pop();if(work_stack.empty()==false){if(work_stack.top().process_flag==0){work_stack.top().process_flag=1;}else{work_stack.top().process_flag=2;}}}}returnroot;}boolisCompeleteBinaryTree(BinaryTree*root){enumFlag{NO_EMPTY,EMPTY}flag=NO_EMPTY;deque<BinaryTree*>work_queue;work_queue.push_back(root);while(work_queue.empty()==false){BinaryTree*cur=work_queue.front();work_queue.pop_front();if(flag==NO_EMPTY){if(cur->left!=nullptr){work_queue.push_back(cur->left);if(cur->right!=nullptr){work_queue.push_back(cur->right);}else{flag=EMPTY;}}else{if(cur->right!=nullptr){returnfalse;}else{flag=EMPTY;}}}elseif(flag==EMPTY){if(cur->left!=nullptr){returnfalse;}elseif(cur->right!=nullptr){returnfalse;}}}returntrue;}BinaryTree*buildBFS(vector<int>&input){structDequeNode{BinaryTree*cur;size_t arrary_index;DequeNode(BinaryTree*c,size_t a):cur(c),arrary_index(a){}};deque<DequeNode>work_queue;BinaryTree*root=newBinaryTree(input[0]);work_queue.push_back(DequeNode(root,1));while(work_queue.empty()==false){size_t temp=0;DequeNode t=work_queue.front();work_queue.pop_front();if((temp=2*t.arrary_index)<=input.size()){t.cur->left=newBinaryTree(input[temp-1]);work_queue.push_back(DequeNode(t.cur->left,temp));if((++temp)<=input.size()){t.cur->right=newBinaryTree(input[temp-1]);work_queue.push_back(DequeNode(t.cur->right,temp));}}}returnroot;}intmain(){vector<int>input{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};BinaryTree*rootDFS=buildDFS(input);BinaryTree*rootBFS=buildBFS(input);if(isCompeleteBinaryTree(rootDFS)){cout<<"DFS建树成功!"<<endl;}else{cout<<"DFS建树失败!"<<endl;}if(isCompeleteBinaryTree(rootBFS)){cout<<"BFS建树成功!"<<endl;}else{cout<<"BFS建树失败!"<<endl;}}