一、题目描述
输入一个只包含0和1的字符串表示二叉树,输出每个节点能到达的最远距离,通过父节点的路径也要考虑。
比如输入"111110000010000", 输出[3,2,4,3,3,4]。
1A
/ \
1B 1C
/ \ / \
1D 1E 0 0
/ \ / \ / \ / \
0 0 0 1F 0 0 0 0
A->B->E->F为3, B->E->F为2,C->A->B->E->F为4,D->B->E->F或D->B->A->C为3,E->B->A->C为3,F->E->B->A->C为4,输出自然为[3,2,4,3,3,4]。
二、解题思路
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// Build tree using level order traversal
TreeNode* buildTree(const string& s) {
if (s.empty() || s[0] == '0') return nullptr;
queue<TreeNode*> q;
TreeNode* root = new TreeNode(1);
q.push(root);
int index = 1;
int currentVal = 2;
while (!q.empty() && index < s.size()) {
TreeNode* node = q.front();
q.pop();
// Left child
if (index < s.size()) {
if (s[index] == '1') {
node->left = new TreeNode(currentVal++);
q.push(node->left);
}
index++;
}
// Right child
if (index < s.size()) {
if (s[index] == '1') {
node->right = new TreeNode(currentVal++);
q.push(node->right);
}
index++;
}
}
return root;
}
unordered_map<TreeNode*, pair<int, int>> dp;
pair<int, int> dfsDown(TreeNode* node) {
if (!node) return {-1, -1}; // Base case: null node has depth -1
auto left = dfsDown(node->left);
auto right = dfsDown(node->right);
int cl = left.first + 1; // Edge count to left child
int cr = right.first + 1;
int longest = max(cl, cr);
int second;
if (cl > cr) {
second = max(left.second + 1, cr);
} else if (cr > cl) {
second = max(cl, right.second + 1);
} else {
second = max(left.second + 1, right.second + 1);
}
dp[node] = {longest, second};
return {longest, second};
}
void dfsUp(TreeNode* node, TreeNode* parent, int up, vector<int>& result) {
if (!node) return;
int currentUp = 0;
if (parent) {
int siblingLongest = -1;
if (parent->left == node && parent->right) {
siblingLongest = dp[parent->right].first;
} else if (parent->right == node && parent->left) {
siblingLongest = dp[parent->left].first;
}
currentUp = max(up + 1, siblingLongest + 2);
}
result[node->val - 1] = max(dp[node].first, currentUp);
dfsUp(node->left, node, currentUp, result);
dfsUp(node->right, node, currentUp, result);
}
vector<int> maxDistances(string s) {
TreeNode* root = buildTree(s);
if (!root) return {};
dp.clear();
dfsDown(root);
int maxNode = 0;
for (auto& pair : dp) maxNode = max(maxNode, pair.first->val);
vector<int> result(maxNode, 0);
dfsUp(root, nullptr, 0, result);
return result;
}
int main() {
string input = "111110000010000";
vector<int> output = maxDistances(input);
for (int dist : output) {
cout << dist << " ";
}
// Output: 3 2 4 3 3 4
return 0;
}