337. 打家劫舍 III*【力扣】

探讨了在二叉树中寻找不相邻节点之间和的最大值的问题,通过递归算法分解为带根节点和不带根节点两种情况,实现代码清晰展示了计算过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意理解

在一个二叉树上遍历,不相邻元素之间的和的最大值

问题分析

递归

分解为带根,不带根两种情况。

其他

链接

    int rob(TreeNode* root) {
        int withRoot = 0, withoutRoot = 0;
        helper (root, withRoot, withoutRoot);
        return max (withRoot, withoutRoot);
    }
    void helper (TreeNode* root, int& withRoot, int& withoutRoot)
    {
        if (!root)
            return;
        int withRootl = 0, withRootr = 0, withoutRootl = 0, withoutRootr = 0;
        helper (root -> left, withRootl, withoutRootl);
        helper (root -> right, withRootr, withoutRootr);
        withRoot = withoutRootl + withoutRootr + root -> val;//带根的最大值等于根值+不带根左子树值+不带根右子树值
        withoutRoot = max (withRootl, withoutRootl) + max (withRootr, withoutRootr);//不带根最大值等于左子树不带根,带根的最大值 + 右子树不带根,带根的最大值??
        
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值