文章
454
粉丝
0
获赞
1
访问
10.6k
二叉树中,若根到某节点的路径上没有比它更大的值,则该节点是关键节点,求个数。
层序(逗号/空格分隔,null 表示空)建树。
从根 BFS,同时携带「路径上的最大值」。
节点值 ≥ 前缀最大值时计数加一。
O(n)。
C++:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Node { int l, r, v; };
static vector<string> split(const string &s) {
vector<string> t;
size_t i = 0;
while (i < s.size()) {
if (s[i] == ',' || s[i] == ' ' || s[i] == '\t' || s[i] == '\r') { i++; continue; }
size_t j = i;
while (j < s.size() && s[j] != ',' && s[j] != ' ' && s[j] != '\t' && s[j] != '\r') j++;
t.push_back(s.substr(i, j - i));
i = j;
}
return t;
}
int main() {
string line;
getline(cin, line);
vector<string> tok = split(line);
if (tok.empty() || tok[0] == "null") { printf("0\n"); return 0; }
vector<Node> tr;
Node root; root.l = root.r = -1; roo...
登录后发布评论
暂无评论,来抢沙发