前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LintCode 二叉树中的最大路径和题目分析代码

LintCode 二叉树中的最大路径和题目分析代码

作者头像
desperate633
发布2018-08-22 11:16:05
4940
发布2018-08-22 11:16:05
举报
文章被收录于专栏:desperate633

题目

给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)

样例 给出一棵二叉树:

Paste_Image.png

返回 6

分析

这道题关于二叉树的最大路径问题,显然需要用递归解决。 由于这道题中所求路径是可以通过根节点的,从任意节点开始和结束的最大路径和。 显然,通过根节点的最大路径=根节点的值,左子树的最大路径+右子树的最大路径 所以我们可以递归求解左右子树的最大路径,最后把他们加到一起就是整个树的最大路径。

代码

代码语言:javascript
复制
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
     

public int maxPathSum(TreeNode root) {
        if(root == null)
            return 0;
        ArrayList<Integer> res = new ArrayList<>();
        res.add(Integer.MIN_VALUE);
        helper(root, res);
        return res.get(0);
    }
    
    private int helper(TreeNode root, ArrayList<Integer> res) {
        if(root == null)
            return 0;
        int left = helper(root.left,res);
        int right = helper(root.right,res);
        
        int cur = root.val + (left>0?left:0) + (right>0?right:0);
        
        if(cur>res.get(0))
            res.set(0, cur);
        
        return root.val + Math.max(left, Math.max(right, 0));
    }
    
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017.02.21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 分析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档