标签:c++ -o software level 输出 brew osi line min
The following is from Max Howell @twitter:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can‘t invert a binary tree on a whiteboard so fuck off.
Now it‘s your turn to prove that YOU CAN invert a binary tree!
Each input file contains one test case. For each case, the first line gives a positive integer N (≤) 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 from 0 to N−1, 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 the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. 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
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
题意:
给出一棵树,将其反转,然后输出层次遍历和中序遍历的结果。
思路:
Invert 的意思就是将每一棵树的左子树和右子树互换,那么我们在输入的时候,就将这一步完成,接下来按照普通的树来建树就好了。
Code:
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 typedef struct Node* node; 6 7 struct Node { 8 int val; 9 node left; 10 node right; 11 Node(int v) { 12 val = v; 13 left = NULL; 14 right = NULL; 15 } 16 }; 17 18 map<int, pair<int, int> > m; 19 node buildTree(int r) { 20 node root = new Node(r); 21 if (m[r].first != -1) { 22 root->left = buildTree(m[r].first); 23 } 24 if (m[r].second != -1) { 25 root->right = buildTree(m[r].second); 26 } 27 return root; 28 } 29 30 void levelOrder(node root) { 31 queue<node> que; 32 que.push(root); 33 bool isFirst = true; 34 while (!que.empty()) { 35 node temp = que.front(); 36 que.pop(); 37 if (isFirst) { 38 cout << temp->val; 39 isFirst = false; 40 } else { 41 cout << " " << temp->val; 42 } 43 if (temp->left) que.push(temp->left); 44 if (temp->right) que.push(temp->right); 45 } 46 cout << endl; 47 } 48 49 bool isFirst = true; 50 void inOrder(node root) { 51 if (root == NULL) return; 52 inOrder(root->left); 53 if (isFirst) { 54 cout << root->val; 55 isFirst = false; 56 } else { 57 cout << " " << root->val; 58 } 59 inOrder(root->right); 60 } 61 62 int main() { 63 int n; 64 cin >> n; 65 vector<int> fa(n, -1); 66 for (int i = 0; i < n; ++i) { 67 char l, r; 68 cin >> l >> r; 69 pair<int, int> temp = {-1, -1}; 70 if (isdigit(l)) { 71 fa[l - ‘0‘] = i; 72 temp.second = l - ‘0‘; 73 } 74 if (isdigit(r)) { 75 fa[r - ‘0‘] = i; 76 temp.first = r - ‘0‘; 77 } 78 m[i] = temp; 79 } 80 int r; 81 for (int i = 0; i < n; ++i) 82 if (fa[i] == -1) r = i; 83 84 node root = buildTree(r); 85 86 levelOrder(root); 87 inOrder(root); 88 cout << endl; 89 90 return 0; 91 }
标签:c++ -o software level 输出 brew osi line min
原文地址:https://www.cnblogs.com/ruruozhenhao/p/12795061.html