找到二叉树中的最大搜索二叉子树

找到二叉树中的最大搜索二叉子树

题目描述:

给定一颗二叉树,已知其中所有节点的值都不一样,找到含有节点最多的搜索二叉子树,输出该子树总节点的数量。

搜索二叉树是指对于二叉树的任何一个节点,如果它有儿子,那么左儿子的值应该小于它的值,右儿子的值应该大于它的值。

输入描述:

第一行输入两个整数 n 和 root,n 表示二叉树的总节点个数,root 表示二叉树的根节点。

以下 n 行每行三个整数 fa,lch,rch,表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理)

ps:节点的编号就是节点的值。

输出描述:

最大的二叉搜索子树节点数目。

示例1
输入
3 2
2 1 3
1 0 0
3 0 0
输出
3
备注:

1 ≤ n ≤ 1 0 6 1 \leq n \leq 10^6 1n106

1 ≤ f a , l c h , r c h , r o o t ≤ n 1 \leq fa,lch,rch,root \leq n 1fa,lch,rch,rootn


题解:

假设当前在 X 节点,分三种情况:

情况一:最大搜索二叉子树来自 X 的左子树;

情况二:最大搜索二叉子树来自 X 的右子树;

情况三:X 为根节点时本身就是一棵搜索二叉树,但需要满足两个条件:

  • X 的左子树和右子树均为搜索二叉树
  • X 的值比左子树的最大值大,比右子树最小值小

然后后序遍历处理上述情况即可。

代码:
#include <cstdio>
#include <algorithm>

using namespace std;

const int N = 1000010;
const int INF = 0x3f3f3f3f;

struct BST {
    int val;
    int lch, rch;
} bst[N];

int n, rt;
int fa, lch, rch;
int ret;

int postorder(int root, int* ans) {
    if (!root) {
        ans[0] = 0, ans[1] = INF, ans[2] = -INF;
        return 0;
    }
    int val = bst[root].val;
    int _lch = bst[root].lch, _rch = bst[root].rch;
    int L = postorder(_lch, ans);
    int lsize = ans[0], lmin = ans[1], lmax = ans[2];
    int R = postorder(_rch, ans);
    int rsize = ans[0], rmin = ans[1], rmax = ans[2];
    int max_size = max(lsize, rsize);
    int head = lsize > rsize ? L : R;
    ans[1] = min(lmin, val);
    ans[2] = max(rmax, val);
    if (L == _lch && R == _rch && lmax < val && rmin > val) {
        max_size = lsize + rsize + 1;
        head = root;
    }
    ans[0] = max_size;
    ret = max(ret, max_size);
    return head;
}

int main(void) {
    scanf("%d%d", &n, &rt);
    while (n--) {
        scanf("%d%d%d", &fa, &lch, &rch);
        bst[fa].val = fa;
        bst[fa].lch = lch;
        bst[fa].rch = rch;
    }
    int ans[3];
    postorder(rt, ans);
    printf("%d\n", ret);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值