zoukankan      html  css  js  c++  java
  • [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>

  • 相关阅读:
    django--orm---006
    django--orm---005
    django--orm---004
    django--orm---003
    jmeter连接数据库
    django--view---001
    django--orm---002
    django--model--orm001-- 增删改查
    java并发编程
    jvm
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/6745161.html
Copyright © 2011-2022 走看看