数据结构 03-树2 List Leaves (25 分)

Posted keiiha

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构 03-树2 List Leaves (25 分)相关的知识,希望对你有一定的参考价值。

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.

Input Specification:

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 N1. 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.

Output Specification:

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.

Sample Input:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
 

Sample Output:

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; }

 

以上是关于数据结构 03-树2 List Leaves (25 分)的主要内容,如果未能解决你的问题,请参考以下文章

03-树2 List Leaves

03-树2 List Leaves (25 分)

03-树2 List Leaves(25 分)

03-树2 List Leaves

List Leaves

数据结构树 —— 编程作业 02 :List Leaves