binary-tree-maximum-path-sum

问题链接:https://www.nowcoder.com/questionTerminal/da785ea0f64b442488c125b441a4ba4a

问题

Given a binary tree, find the maximum path sum.The path may start and end at any node in the tree.
For example:
Given the below binary tree,

   1
  / \
 2   3

Return6.

求二叉树的最大路径和。路径的起点和终点可以是任意节点。

分析

二叉树里的任何路径都是二叉树,都有根节点。所以问题等价如下:
通过根节点的最大路径和,而二叉树的每个节点都可以是根节点,所以分别求出以每个节点为根节点的二叉树中通过根节点的最大路径和,并比较出最大的即可。

代码

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}
import java.util.ArrayList;

public class Solution {
    public int maxPathSum(TreeNode root) {
        if (root == null) {
            return 0;
        }

        // 通过每个根节点的路径和数组
        ArrayList<Integer> paths = new ArrayList<>();
        rootMaxPath(root, paths);

        int max = paths.get(0);
        int size = paths.size();
        for (int i = 1; i < size; i++) {
            if (paths.get(i) > max) {
                max = paths.get(i);
            }
        }

        return max;
    }

    /**
     * 求二叉树最大的半边路径和(包含根节点)
     * 
     * @param root
     *            根节点
     * @param paths
     *            通过每个根节点的路径和数组
     * @return
     */
    private int rootMaxPath(TreeNode root, ArrayList<Integer> paths) {
        if (null == root) {
            return 0;
        }

        int path = root.val;
        int lmax = rootMaxPath(root.left, paths);
        int rmax = rootMaxPath(root.right, paths);

        if (lmax > 0) {
            path += lmax;
        }
        if (rmax > 0) {
            path += rmax;
        }
        paths.add(path);

        int max = Math.max(lmax, rmax);
        return root.val + Math.max(max, 0);
    }
}
点赞