题目描述
二叉树用数组存储,将二叉树的结点数据依次自上而下,自左至右存储到数组中,一般二叉树与完全二叉树对比,比完全二叉树缺少的结点在数组中用0来表示。
计算二叉树每个结点的平衡因子,并按后序遍历的顺序输出结点的平衡因子。
–程序要求–
若使用C++只能include一个头文件iostream;若使用C语言只能include一个头文件stdio
程序中若include多过一个头文件,不看代码,作0分处理
不允许使用第三方对象或函数实现本题的要求
输入
测试次数t
每组测试数据一行,数组元素个数n,后跟n个字符,二叉树的数组存储。
输出
对每组测试数据,按后序遍历的顺序输出树中结点的平衡因子(测试数据没有空树)
样例查看模式
正常显示
查看格式
输入样例1 <-复制
2
6 ABC00D
24 ABCD0EF0000H00000000000I
输出样例1
B 0
D 0
C 1
A -1
D 0
B 1
I 0
H 1
E 2
F 0
C 2
A -2
#include <iostream>
using namespace std;
class node{
public:
char val;
node *left,*right;
node(){
val='0';left= nullptr;right= nullptr;
}
};
class tree{
public:
void init(){
int t;cin>>t;
node **s=new node*[t];
for (int i = 0; i < t; ++i) {
s[i]=new node();
cin>>s[i]->val;
}
int p=0;int q=1;
for (int i = 0; i < t; ++i) {
if(q<t)
s[p]->left=s[q];
if(q+1<t)
s[p]->right=s[q+1];
q++;p++;q++;
}
pre(s[0]);
after(s[0]);
}
int findheight(node *p){
if(!p)return -1;
int l=0;int r=0;
if(p->left)
l= findheight(p->left)+1;
if(p->right)
r= findheight(p->right)+1;
return l>r?l:r;
}
void after(node *p){
if(p->left)after(p->left);
if(p->right)after(p->right);
cout<<p->val<<" "<<findheight(p->left)- findheight(p->right)<<endl;
}
void pre(node *p){
if(p->left)
if(p->left->val=='0')
p->left= nullptr;
if(p->right)
if(p->right->val=='0')
p->right= nullptr;
if(p->left)
pre(p->left);
if(p->right)
pre(p->right);
}
};
int main(){
int t;cin>>t;
while (t--){
tree t;
t.init();
}
}