题解 | #二叉树中的最大路径和,dfs + 记忆化搜索 + hashMap,垃圾解法#

二叉树中的最大路径和

http://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    
    int max = Integer.MIN_VALUE ;
    HashMap<TreeNode , Integer> map = new HashMap<>() ;
    HashMap<TreeNode , Integer> map2 = new HashMap<>() ;
    public int maxPathSum (TreeNode root) {
        if(root == null) return 0 ;
        pre(root) ;
        return max ;
    }
    //中序遍历
    public void pre(TreeNode root) {
        if(root == null) return ;
        int one = help(root) ;
        int two = map2.get(root) ;
        int res = max(one , two) ;
        max = max(res , max) ;
        pre(root.left) ;
        pre(root.right) ;
    }
    public int help(TreeNode root) {
        if(root == null) return -1001 ;
        Integer get = map.get(root) ;
        if(get != null) return get ;
        if(root.left == null && root.right == null) {
            map.put(root , root.val) ;
            map2.put(root , root.val) ;
            return root.val ;
        } 
        int l = help(root.left) ;
        int r = help(root.right) ;
        int res = max(l + root.val , r + root.val , root.val) ;
        map.put(root , res) ;
        map2.put(root , l + r + root.val) ;
        return res ;
        
    }
    public int max(int...args) {
        int max = Integer.MIN_VALUE ;
        for(int a : args) {
            if(a > max) {
                max = a ;
            }
        }
        return max ;
    }
}

一个菜鸟的算法刷题记录 文章被收录于专栏

分享一个菜鸟的成长记录

全部评论

相关推荐

每晚夜里独自颤抖:把华北改为华南再试一试,应该就没啥问题了。改完可能都不用投,别人主动联系了。
点赞 评论 收藏
分享
深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务