839 - Not so Mobile

本文介绍了一种通过遍历检查二叉树是否满足特定平衡条件的方法。利用递归方式创建二叉树,并通过比较各节点子树的权值与深度来判断整个树的平衡性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* 解题思路: 创建二叉树 遍历检查 这道题其实不需要建立树的结构,因为遍历检查可以在创建时就能完成 需要用到数组做存储结构 */ #include <iostream> #include <string> #include <cstdio> #include <cstdlib> using namespace std; struct Node { int w1,d1,w2,d2; Node *lchild,*rchild; }; bool isEqual; Node *createTree() { int w1,d1,w2,d2; cin>>w1>>d1>>w2>>d2; Node *root=(Node *)malloc(sizeof(Node)); root->w1=w1; root->d1=d1; root->w2=w2; root->d2=d2; if(w1==0) root->lchild=createTree(); else root->lchild=NULL; if(w2==0) root->rchild=createTree(); else root->rchild=NULL; return root; } int check(Node *root) { if(root->lchild!=NULL) root->w1=check(root->lchild); if(root->rchild!=NULL) root->w2=check(root->rchild); if(isEqual==true) //这里有个技巧****** isEqual=(root->w1*root->d1==root->w2*root->d2); /* 另一种表示形式 if(root->w1*root->d1!=root->w2*root->d2) isEqual=false; */ return root->w1+root->w2; } int main() { //freopen("data.in","r",stdin); int T; cin>>T; while(T--) { Node *root=createTree(); isEqual=true; check(root); cout<<(isEqual?"YES":"NO")<<endl; //The outputs of two consecutive cases will be separated by a blank line. if(T!=0)//仔细看题,WA原因 cout<<endl; } return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值