当前位置:网站首页>Invert a Binary Tree
Invert a Binary Tree
2022-07-27 05:01:00 【Small l ~~~】
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!
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 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.
Output Specification:
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.
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
The main idea of the topic :
Swap the left and right subtrees of a binary tree , And output the sequence traversal and middle sequence traversal after exchange .
ps:( The title is not difficult. , I wrote this blog because there is an algorithm problem in the chapter of binary tree in Wang daoshu, which is to exchange the left of binary tree 、 Right subtree , Happened to be here today pta See this problem above , Just do it by the way , Then write this blog , I hope that helps .)
Their thinking : Recursive algorithm is used to realize the left-hand transformation of commutative binary tree 、 Right subtree , First exchange nodes k The left of the child 、 Right subtree , Exchange again k The right of the node, the left of the child 、 Right subtree , Finally exchange k The left side of the node 、 The right child , When the node is empty, the recursion ends .
#include<bits/stdc++.h>
using namespace std;
struct binary_tree
{
int data;
int lchild, rchild;
}node[15];
int n;
bool visited[15] = {
false};
int build_tree() {
scanf("%d", &n);
char left, right;
for(int i = 0; i < n; i++) {
node[i].data = i;
cin >> left >> right;
if(left == '-') node[i].lchild = -1;
else {
node[i].lchild = (left - '0');
visited[left - '0'] = true;
}
if(right == '-') node[i].rchild = -1;
else {
node[i].rchild = (right - '0');
visited[right - '0'] = true;
}
}
for(int i = 0; i < n; i++) {
// Return root node
if(!visited[i]) return i;
}
}
void invert(int k) {
// Recursively swap left 、 Right subtree
if(k == -1) return;
invert(node[k].lchild);
invert(node[k].rchild);
swap(node[k].lchild, node[k].rchild);
}
void levelorder(int root) {
// Sequence traversal
queue<binary_tree>q;
q.push(node[root]); // Root in line
vector<int> ans;
while(!q.empty()) {
binary_tree top = q.front();
q.pop();
ans.push_back(top.data);
if(top.lchild != -1) q.push(node[top.lchild]);
if(top.rchild != -1) q.push(node[top.rchild]);
}
printf("%d", ans[0]);
for(int i = 1; i < ans.size(); i++) printf(" %d", ans[i]);
puts("");
}
vector<int>inorder_ans; // To ensure that no extra spaces are output when the last node is output , First save the answers with an array
void inorder(int k) {
// In the sequence traversal
if(k == -1) return;
inorder(node[k].lchild);
inorder_ans.push_back(node[k].data);
inorder(node[k].rchild);
}
void print_inorder() {
// Print the middle order traversal sequence
printf("%d", inorder_ans[0]);
for(int i = 1; i < inorder_ans.size(); i++) printf(" %d", inorder_ans[i]);
}
int main() {
int root = build_tree();
// for(int i = 0; i < n; i++) {
// cout << node[i].lchild << " " << node[i].rchild << endl;
// }
// cout << endl;
invert(root);
// for(int i = 0; i < n; i++) {
// cout << node[i].lchild << " " << node[i].rchild << endl;
// }
levelorder(root);
inorder(root);
print_inorder();
return 0;
}
边栏推荐
- Cache read / write policies: cacheside, read/writethrough and writeback policies
- Row, table, page, share, exclusive, pessimistic, optimistic, deadlock
- Be diligent in talking about what sidelines you can do now
- Two way republication experiment
- There is no need to install CUDA and cudnn manually. You can install tensorflow GPU through a one-line program. Take tensorflow gpu2.0.0, cuda10.0, cudnn7.6.5 as examples
- Why is select not recommended*
- 勤于奋聊聊现在还有哪些副业可以做
- Hiding skills of Photoshop clipping tool
- 对话框数据传递
- static和final关键字 学习 demo练习
猜你喜欢

Unit test Chapter6

消防安全培训资料汇总

Network protocol details: IP

MySQL download and installation & perfect uninstall

CDH cluster integration external Flink (improved version - keep pace with the times)

"Photoshop2021 tutorial" adjust the picture to different aspect ratio

Structural mode - adapter mode

How do I reset Photoshop preferences? PS method of resetting preferences

Comprehensive experiment of static routing

Find a specific number in an ordered array
随机推荐
Why is select not recommended*
再一个技巧,每月稳赚3万+
消防安全培训资料汇总
Unit test Chapter6
写代码涉及到的斜杠/和反斜杠\
[search] two way search + A*
Photoshop裁剪工具隐藏技巧
Review of various historical versions of Photoshop and system requirements
How do I reset Photoshop preferences? PS method of resetting preferences
Plato farm is expected to further expand its ecosystem through elephant swap
缓存读写策略:CacheAside、Read/WriteThrough及WriteBack策略
Stm32 cubemx hal----- PWM - change frequency
C语言 通讯录管理系统(链表,手机号码分段存储,txt文件存取,完整源码)
.htaccess learning
Solution: how to use bash batch command in win10
HCIA dynamic routing OSPF experiment
事件(event)
多态的详讲
MySQL下载安装 & 完美卸载
如何将Photoshop图层复制到其他文档