zoukankan      html  css  js  c++  java
  • 03.树2 List Leaves [层序遍历+建树]

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

    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<queue>
    #define max 100 
    #define NULL -1
    using namespace std;
    int nn;
    struct node {
    	int left;
    	int right;
    }tree1[max];            //静态链表的使用 
    int create(struct node tree[],int n) {
    	int i,root = NULL;
    	scanf("%d", &n);
    	nn = n;
    	int* arr = new int[n + 1];
    	fill(arr, arr + n, 0);
    	char ch1, ch2;          //左子节点 右子节点输入 用char类型因为含有'-'; 
    	for (i = 0; i < n; i++) {                 //利用没有父节点指向根节点,找出根节点
    		getchar();           ///
    		scanf("%c %c", &ch1, &ch2);
    		if (ch1 != '-') {
    			tree[i].left = ch1 - '0';
    			arr[tree[i].left] = 1;
    		}
    		else tree[i].left = NULL;
    		if (ch2 != '-') {
    			tree[i].right = ch2 - '0';
    			arr[tree[i].right] = 1;
    		}
    		else tree[i].right = NULL;
    	}
    	for (i = 0; i < n; i++) {
    		if (!arr[i]) {
    			root = i;
    			break;
    		}
    	}
    	delete[]arr;
    	return root;
    }
    void levelorder(int root) {
    	queue<int>q;
    	int i;
    	int num = 0;
    	q.push(root);
    	while (!q.empty()) {
    		num++;
    		i = q.front();
    		q.pop();             //queue 和 stack的pop没有返回值的 
    		if (tree1[i].left != NULL && tree1[i].right != NULL) {
    			q.push(tree1[i].left);
    			q.push(tree1[i].right);
    		}
    		else if (tree1[i].left != NULL && tree1[i].right == NULL) {
    			q.push(tree1[i].left);
    		}
    		else if (tree1[i].left == NULL && tree1[i].right != NULL) {
    			q.push(tree1[i].right);
    		}
    		else {
    			if (num != nn) printf("%d ", i);
    			else printf("%d", i);
    		}
    	}
    }
    int main() {
    	int root = create(tree1,nn);
    	levelorder(root);
    	return 0;
    }
    
    
  • 相关阅读:
    顺序表
    顺序表实验2
    C艹不使用库函数简陋实现strlen
    数据结构化与保存
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    词频统计
    组合数据类型练习,综合练习
    Python基础综合练习
    熟悉常用的Linux操作
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13109985.html
Copyright © 2011-2022 走看看