• [LeetCode][Java] Binary Tree Maximum Path Sum


    题目:

    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
    

    Return 6.

    题意:

    给定一棵二叉树,找出最大得路径和。

    路径的起始和结束位置能够是树中的随意节点。

    比方,

    给定例如以下的一棵二叉树

           1
          / 
         2   3
    返回  6.

    算法分析:

        1) Recursively solve this problem

        2) Get largest left sum and right sum

        3) Compare to the stored maximum

      * 这里有一个地方要想明确,最短路径结果有四种可能,当前加左,当前加右。当前自己,当前加左、右子树的return值

      * 而return值,有三种可能,当前加左,当前加右。当前自己。

      * 这里return里不是当前加左右子树,也就是不能把left和right加起来了...由于仅仅是一条路..,故不符合题目要求。

      * 在这里,函数的返回值定义为以自己为根的一条从根到子结点的最长路径


    AC代码:

    <span style="font-family:Microsoft YaHei;font-size:12px;">/**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution 
    {
        public int maxPathSum(TreeNode root) 
        {
        	int max[] = new int[1]; 
        	max[0] = Integer.MIN_VALUE;
        	calculateSum(root, max);
        	return max[0];
        }
         
        public int calculateSum(TreeNode root, int[] max) 
        {
        	if (root == null)
        		return 0;
         
        	int left = calculateSum(root.left, max);
        	int right = calculateSum(root.right, max);
         
        	int current = Math.max(root.val, Math.max(root.val + left, root.val + right));
         
        	max[0] = Math.max(max[0], Math.max(current, left + root.val + right));
         
        	return current;
        }
    }</span>

  • 相关阅读:
    asp .net 页面回车触发button 按钮事件
    Asp.netPost&Get转
    2012.8.16近期总结,1模态窗口回传重新被弹出2,清空缓存 3,
    面试感言
    2012.6.27近期总结,1.sql字符串转换(cast,CONVERT )调用wcf服务,关闭模态窗口刷新付页面
    self
    空指针
    枚举和结构体
    typedef
    指针
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/6745161.html
Copyright © 2020-2023  润新知