struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() { val = 0, left = nullptr, right = nullptr; } }; // 判断node是否在以root为头节点的搜索二叉树上 bool isBSTNode(TreeNode *root, TreeNode *node) { if (!root) return false; if (root == node) return true; return isBSTNode( (root->val > node->val) ? root->left : root->right, node); } // 搜索以root为头节点的最大拓扑结构 int getSizeFromNode(TreeNode *root, TreeNode *cur) { if (!root || !cur) return 0; if (!isBSTNode(root, cur)) return 0; // 以root为头节点的满足要求,继续从左右子树开始搜索 return 1 + getSizeFromNode(root, cur->left) + getSizeFromNode(root, cur->right); } void getMaxTopSize(TreeNode *root,int &ans) { if (!root) return; ans = max(ans, getSizeFromNode(root, root)); getMaxTopSize(root->left, ans); getMaxTopSize(root->right, ans); } int main() { #ifdef LOCAL freopen("../leetcode/in.txt", "r", stdin); #endif int n, root, ans = 0; int rt, l, r; cin >> n >> root; vector<TreeNode> tree(n + 1); for (int i = 0; i < n; i++) { cin >> rt >> l >> r; tree[rt].val = rt; if (l) tree[rt].left = &tree[l]; if (r) tree[rt].right = &tree[r]; } getMaxTopSize(&tree[root], ans); cout << ans << endl; return 0; }