leetcode--Binary Tree Maximum Path Sum

本文介绍了一种使用深度优先搜索(DFS)算法解决二叉树中寻找最大路径和问题的方法。通过递归地计算每个节点的最大贡献值,并维护全局最大路径和来找到最终答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:以采用Binary Tree最常用的dfs来进行遍历。先算出左右子树的结果L和R,如果L大于0,那么对后续结果是有利的,我们加上L,如果R大于0,对后续结果也是有利的,继续加上R。

[java]  view plain  copy
  1. /** 
  2.  * Definition for a binary tree node. 
  3.  * public class TreeNode { 
  4.  *     int val; 
  5.  *     TreeNode left; 
  6.  *     TreeNode right; 
  7.  *     TreeNode(int x) { val = x; } 
  8.  * } 
  9.  */  
  10. public class Solution {  
  11.     public int maxPathSum(TreeNode root) {  
  12.         max = Integer.MIN_VALUE;  
  13.         dfs(root);  
  14.         return max;  
  15.     }  
  16.       
  17.     int max = 0;//最大值  
  18.     /** 
  19.      * 该方法返回包含t节点的最大路径和  
  20.      */  
  21.     int dfs(TreeNode t){  
  22.         if(t==nullreturn 0;//如果为空,路径和为0  
  23.         int left = dfs(t.left);//包含左节点的最大路径和left  
  24.         int right = dfs(t.right);//包含右节点的最大路径和right  
  25.         int curmax = t.val;//当前节点,当前和  
  26.         if(left>0) curmax += left;//如果左节点不为0,加上  
  27.         if(right>0) curmax += right;//如果右节点不为0,也加上  
  28.         max = Math.max(max,curmax);//与当前最大值比较,更新  
  29.         if(left>0||right>0){//如果左节点或者右节点,大于0  
  30.             return left>right?left+t.val:right+t.val;  
  31.         }else{//如果左右节点都是负数或者0,返回当前节点值即可  
  32.             return t.val;  
  33.         }  
  34.     }  
  35. }  

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46836605

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值