1372. 二叉树中的最长交错路径(逐句解释代码)

61 篇文章 0 订阅
解题思路

res[0]表示当前节点下一步向左走带来的最大收益,res[1]表示当前节点下一步向右走带来的最大收益
res[0]=1+left[1] 当前节点下一步向左走带来的最大收益等于左子节点向右走的最大收益+1
res[1]=1+right[0] 当前节点下一步向右走带来的最大收益等于右子节点向左走的最大收益+1

package LeetCode.OneThousandMore;

import LeetCode.TreeNode;

public class OneThousandThreeHundredAndSeventhTwo {
    private int max;
    public int longestZigZag(TreeNode root) {
        // 一道很明显的dp题
        helper(root);
        return max;
    }
    private int[] helper(TreeNode root) {
        int[] res = new int[2];
        // 用res[0]来表示当前节点走左子树最大的值,res[1]表示右子树最大的值
        if (root == null){
            res[0] = res[1] = -1;
            return res;
        }
        int[] left = helper(root.left);
        int[] right = helper(root.right);
        // 因为是交叉的,所以当前是左下一个就要访问右子树,右子树则相反
        res[0] = left[1] + 1;
        res[1] = right[0] + 1;
        max = Math.max(max,Math.max(res[0], res[1]));
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值