网易笔试第二题C++版,一目了然

//数据读取部分费劲,重建二叉树还好解决

#include<stdio.h>
#include<iostream>
#include<vector>
#include<queue>
#include <string>

using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) { val = x; }
};
TreeNode* creat(int id, vector<vector<int> > v1) {//rebuild 二叉 tree
int r = v1[id][0];
TreeNode* root = new TreeNode(r);
int le = v1[id][1];
int ri = v1[id][2];
if (le == -1)
root->left = NULL;
else
root->left = creat(le, v1);

if (ri == -1)
root->right = NULL;
else
root->right = creat(ri, v1);
return root;
}
string F(TreeNode* root) {//判断yes or no
int sum1 = 0;
int sum2 = 0;
queue<TreeNode*>que1;
queue<TreeNode*>que2;
que1.push(root);
int count = 0;
TreeNode *q1 = que1.front();
sum1 += q1->val;
while (!que1.empty()) {
while (!que1.empty()) {
TreeNode *q = que1.front();
que1.pop();
if (q->left != NULL) {
que2.push(q->left);
sum2 += q->left->val;
}
if (q->right != NULL) {
que2.push(q->right);
sum2 += q->right->val;
}
}
if (que2.empty())
break;
if (que1.empty()) {
que1 = que2;
while (!que2.empty()) que2.pop();
}
if (sum1 >= sum2)
return "NO";
sum1 = sum2;
sum2 = 0;

}
return "YES";
}

int main() {
int n;
vector<string> result;

while (cin >> n) {
if (cin.get() == '\n')
break;
}
for (int d = 0; d < n;d++){
vector<vector<int> > t2;
int m;
while (cin >> m) {
if (cin.get() == '\n')
break;
}

int r = 0;
int a = 0;
for (int j = 0; j < m; j++) {
string str;
r += j;
getline(cin, str);
vector<int> t1;

for (int k = 0; k < str.size(); k++) {

string str2 = "";
while (str[k] != ' '&& k < str.size()) {
str2 += str[k];
k++;
}
int tmp = stoi(str2);
t1.push_back(tmp);
}

if (t1[1] != -1) a += t1[1];
if (t1[2] != -1) a += t1[2];

t2.push_back(t1);
}
r = r - a;
TreeNode* roo = creat(r, t2);
result.push_back(F(roo));
}
//************//result/*//////*******
for (int i = 0; i < result.size(); i++)
cout << result[i] << endl;
system("pause");
}
#笔试题目##网易##C/C++#
全部评论

相关推荐

Java面试先知:我也是和你一样的情况,hr 说等开奖就行了
点赞 评论 收藏
分享
评论
1
3
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务