Comments (3)
收到,谢谢你的提示,题解 已修改
from ustc-cs-graduate.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() {};
TreeNode(int x) :val(x) {};
TreeNode(int x, TreeNode* l, TreeNode* r) :val(x), left(l),right(r) {};
};
struct info {
int low;
int up;
info(int a, int b) : low(a), up(b) {};
};
int gb_ret;
int maxChainLen(TreeNode* root) {
if (!root) return 0;
int llen = maxChainLen(root->left);
int rlen = maxChainLen(root->right);
//若去掉这行关于全局变量gb_ret的代码,那maxChainLen就是求从某个结点向下的最长路径
//若保留,则:
//每次递归走到此处时,我们已经知道了从左、右走的两条最长路,那么我们也就知道了在该点“拐弯”的最长路径
//又由于maxChainLen会遍历所以结点,那我们相应地也就穷举了在所有点“拐弯”的路径
gb_ret = fmax(root->val + llen + rlen, gb_ret);
return fmax(llen, rlen) + root->val;
}
void t5() {
int k;
ifstream fin("tree.in");
TreeNode* root;
queue<pair<TreeNode**, info*>> q;
pair<TreeNode**, info*> rootpair = { &root, new info(-1,INT32_MAX) };
q.push(rootpair);
while (fin >> k) {
TreeNode** T;
info* ifm;
while (true) {
T = q.front().first;
ifm = q.front().second;
q.pop();
if (ifm->low < k && k < ifm->up) {
break;
}
}
*T = new TreeNode(k, NULL, NULL);
//注意->优先于&
pair<TreeNode**, info*> leftpair = { &(*T)->left, new info(ifm->low, k) };
pair<TreeNode**, info*> rightpair = { &(*T)->right, new info(k,ifm->up) };
q.push(leftpair);
q.push(rightpair);
}
gb_ret = -1;
maxChainLen(root);
cout << gb_ret;
}
from ustc-cs-graduate.
输入示例:
25 15 40 5 20 30 50 10 35
输出示例:
165
from ustc-cs-graduate.
Related Issues (3)
- 对20年机考题第三题的疑问 HOT 1
- 2019年机试第五题捉个虫 HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from ustc-cs-graduate.