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

    思路:本人脑子笨。一開始想了好久都木有思路,仅仅有一个笨办法:把全部的叶子i到叶子节点j的路径都遍历一遍。近期写回溯法用递归用的多,我突然想到了递归能够。用一个全局变量max来存储最大值,然后再求最大连续子序列和。如果我们已经知道了某个节点node的左右子树的最大路径和leftmaxsum。rightmaxsum。那么这个节点node的最大路径和为Math.max(node.val,Math.max(node.val+leftmaxsum,node.val+rightmaxsum));这个节点node的最大路径和仅仅是为了给node的父节点准备的,并不是给node自己准备的。

    那么给node准备用啥呢---max。        temp=root.val+leftmaxsum+rightmaxsum; max=max>temp?max:temp;  这样max就能返回当前的最大路径和。代码例如以下:

    public class Solution {
    	static int max = Integer.MIN_VALUE;
    
    	public int maxPathSum(TreeNode root) {
    		max = Integer.MIN_VALUE;
    		PathSum(root);
    		return max;
    	}
    
    	public int PathSum(TreeNode root) {
    		if(root==null) return 0;
    		int leftmaxsum=0;
    		int rightmaxsum=0;
    		int temp=root.val;
            if(root.left!=null){
            	leftmaxsum=Math.max(PathSum(root.left),0);
            } 
            if(root.right!=null){
            	rightmaxsum=Math.max(PathSum(root.right),0);
            }
            temp=root.val+leftmaxsum+rightmaxsum;
            max=max>temp?max:temp;
            return Math.max(root.val,Math.max(root.val+leftmaxsum, root.val+rightmaxsum));
        }
    }


  • 相关阅读:
    [HNOI2002]营业额统计
    HDU 1374
    HDU 3345
    HDU 2089
    Graham扫描法
    Codeforces 1144D Deduction Queries 并查集
    Codeforces 916E Jamie and Tree 线段树
    Codeforces 1167F Scalar Queries 树状数组
    Codeforces 1167E Range Deleting
    Codeforces 749E Inversions After Shuffle 树状数组 + 数学期望
  • 原文地址:https://www.cnblogs.com/jhcelue/p/7323611.html
Copyright © 2011-2022 走看看