leetcode解题之124. Binary Tree Maximum Path Sum Java版 (二叉树的最大路径和)

来源:互联网 发布:网络公开课英语作文 编辑:程序博客网 时间:2024/06/07 10:35

124. Binary Tree Maximum Path Sum

Given a binary tree, find the 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 containat least one node and does not need to go through the root.

For example:
Given the below binary tree,

       1      / \     2   3

Return 6.

计算二叉树中的路径之和最大值,起止节点为任意(此题和求二叉树的直径差不多,参考)

543. Diameter of Binary Tree Java版 (二叉树的最大直径)

private int maxVal = Integer.MIN_VALUE;public int maxPathSum(TreeNode root) {if (root == null)return 0;maxCore(root);return maxVal;}// 该函数返回是左右的最大路径和,而非左+右+root的最大值// 使用curValue,来标记左+右+rootprivate int maxCore(TreeNode root) {if (root == null)return 0;// 求以root为根的当前子树的最大路径和// 如果左右子树都是负数,// 那么就最大路径就是当前结点值(无论正负)int curValue = root.val;int lmax = maxCore(root.left);int rmax = maxCore(root.right);if (lmax > 0)curValue += lmax;if (rmax > 0)curValue += rmax;maxVal = Math.max(curValue, maxVal);// 返回以当前root为根的子树的最大路径和// 左右有可能都为负数,所以需要参与比较大小int thisMax = Math.max(root.val, Math.max(lmax + root.val, rmax + root.val));return thisMax;}



0 0