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

    解题思路:

    DFS暴力枚举,注意,如果采用static 全局变量的话,在IDE里面是可以通过,但在OJ上无法测试通过,因此需要建立一个类来储存结果,JAVA实现如下:

    public class Solution {
    	static public int maxPathSum(TreeNode root) {
    		Result result=new Result(Integer.MIN_VALUE);
    		dfs(root,result);
    		return result.val;
    	}
    	static int dfs(TreeNode root,Result result) {
    		if (root == null)
    			return 0;
    		int left_sum = Math.max(0, dfs(root.left,result));
    		int right_sum = Math.max(0, dfs(root.right,result));
    		result.val = Math.max(result.val, left_sum + right_sum + root.val);
    		return Math.max(left_sum, right_sum) + root.val;
    	}
    }
    class Result{
    	int val;
    	Result(){
    		this.val=Integer.MIN_VALUE;
    	}
    	Result(int val){
    		this.val=val;
    	}
    }
    
  • 相关阅读:
    电脑不能连接到热点
    常用网络协议
    HVV面试
    【转载】hacker术语
    渗透测试学习路线
    系统安全——可信计算
    rsync文件同步详解
    rabbitmq集群部署高可用配置
    ansible自动化部署之路笔记
    ELK-elasticsearch-6.3.2部署
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4531152.html
Copyright © 2011-2022 走看看