Sicily-1156

一.      模仿树的的先序遍历。范围是1000个节点。用数组存储节点的信息。

二.      要注意的是,头结点是不确定的,所以在前序遍历之前要找出头结点,除了头结点的下标值出现一次之外,其他结点的下标值都会出现两次,根据这个特征可以利用异或运算(^),算出头结点。

三.      源码

 1 //

 2 //  main.cpp

 3 //  sicily-1156

 4 //

 5 //  Created by ashley on 14-10-12.

 6 //  Copyright (c) 2014年 ashley. All rights reserved.

 7 //

 8 

 9 #include <iostream>

10 using namespace std;

11 typedef struct

12 {

13     char element;

14     int leftChild;

15     int rightChild;

16 }node;

17 node binaryTree[1001];

18 void preorder(int front)

19 {

20     cout << binaryTree[front].element;

21     if (binaryTree[front].leftChild != 0) {

22         preorder(binaryTree[front].leftChild);

23     }

24     if (binaryTree[front].rightChild != 0) {

25         preorder(binaryTree[front].rightChild);

26     }

27 }

28 int main(int argc, const char * argv[])

29 {

30     int counts = 0;

31     char ele;

32     int number;

33     int left, right;

34     while (cin >> counts) {

35         int source = 0;

36         for (int i = 0; i < counts; i++) {

37             cin >> number >> ele >> left >> right;

38             source = source ^ left ^ right ^ number;

39             binaryTree[number] = node{ele, left, right};

40         }

41         preorder(source);

42         cout << endl;

43     }

44     return 0;

45 }

 

你可能感兴趣的:(CI)