标签:序号 tree position efault air vector numbers algorithm traversal
Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.
Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N?1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a "-" will be put at the position. Any pair of children are separated by a space.
For each test case, print in one line all the leaves‘ indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
4 1 5
#include <iostream> #include <vector> #include <algorithm> using namespace std; class tnode{ public: int left{-1}; int right{-1}; tnode()=default; }; int init(vector<tnode> &t){// 建树 返回树的根在数组中的坐标 int n,root; string templ,tempr; cin >> n; vector<int> notRootList(n,0); for(int i=0;i<n;i++){ cin >> templ >> tempr; tnode node; if(templ!="-"){ node.left=stoi(templ); notRootList[node.left]=1; } if(tempr!="-"){ node.right=stoi(tempr); notRootList[node.right]=1; } t.push_back(node); } for(int i=0;i<n;i++){ if(notRootList[i]==0){ root=i; break; } } return root;//根的序号 }
//层序遍历 void levelOrderTraversal(vector<tnode> &t,int root,vector<int> &leafList){ vector<int> levelOrder; int index; levelOrder.push_back(root); while(levelOrder.size()){ index=levelOrder.front(); if(t[index].left==-1&&t[index].right==-1){ leafList.push_back(index); } if(t[index].left!=-1){ levelOrder.push_back(t[index].left); } if(t[index].right!=-1){ levelOrder.push_back(t[index].right); } vector<int>::iterator it; it=find(levelOrder.begin(),levelOrder.end(),index); levelOrder.erase(it); } } void printLeafs(vector<int> leafs){ for(int i=0;i<leafs.size();i++){ if(i!=leafs.size()-1){ cout << leafs[i]<<" "; }else{ cout <<leafs[i]<<endl; } } } int main(){ int root; vector<int> leafList; vector<tnode> t; root=init(t); levelOrderTraversal(t, root, leafList); printLeafs(leafList); return 0; }
标签:序号 tree position efault air vector numbers algorithm traversal
原文地址:https://www.cnblogs.com/ichiha/p/14778423.html