LeetCode--124--hard--BinaryTreeMaximumPathSum

和自甴很熟 提交于 2019-12-16 06:17:19
package com.app.main.LeetCode.tree;

import com.app.main.LeetCode.base.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * 124
 *
 * hard
 *
 * Given a non-empty binary tree, find the maximum path sum.
 *
 * https://leetcode.com/problems/binary-tree-maximum-path-sum/
 *
 * For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
 *
 * Example 1:
 *
 * Input: [1,2,3]
 *
 *        1
 *       / \
 *      2   3
 *
 * Output: 6
 * Example 2:
 *
 * Input: [-10,9,20,null,null,15,7]
 *
 *    -10
 *    / \
 *   9  20
 *     /  \
 *    15   7
 *
 * Output: 42
 *
 *
 * Created with IDEA
 * author:Dingsheng Huang
 * Date:2019/12/3
 * Time:下午6:56
 */
public class BinaryTreeMaximumPathSum {
    // dp cache
    Map<TreeNode, Integer> cache = new HashMap<>();

    // result
    Integer max = -Integer.MAX_VALUE;

    public int maxPathSum(TreeNode root) {
        postorder(root);
        return max;
    }
    private void postorder(TreeNode curr) {
        if (curr!= null) {
            if (curr.left != null) {
                postorder(curr.left);
            }
            if (curr.right != null) {
                postorder(curr.right);
            }
            // post order todo
            if (curr.left == null && curr.right == null) {
                cache.put(curr, curr.val);
                max = Math.max(curr.val, max);
            } else {
                int currMax = curr.val;
                int lMax = curr.val;
                int rMax = curr.val;
                if (curr.left != null) {
                    int l = cache.get(curr.left);
                    currMax = Math.max(currMax, (currMax + l));
                    lMax = Math.max(lMax, (curr.val + l));
                }
                if (curr.right != null) {
                    int r = cache.get(curr.right);
                    currMax = Math.max(currMax, (currMax + r));
                    rMax = Math.max(rMax, (curr.val + r));
                }
                cache.put(curr, Math.max(lMax, rMax));
                max = Math.max(currMax, max);
            }
        }
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!