博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Binary Tree Maximum Path Sum
阅读量:4669 次
发布时间:2019-06-09

本文共 811 字,大约阅读时间需要 2 分钟。

题目:

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 4
/ \
2 3
The highlighted path yields the maximum sum 10

 

解答:

1 public class Solution { 2     private int maxSum; 3  4     public int getPathSum(TreeNode root) { 5         maxSum = Integer.MIN_VALUE; 6         findMax(root); 7         return maxSum; 8     } 9 10     private int findMax(TreeNode p) {11         if(p == null) {12             return 0;13         }14 15         int left = findMax(p.left);16         int right = findMax(p.right);17 18         maxSum = Math.max(p.val + left + right, maxSum);19         int ret = p.val + Math.max(left, right);20         return ret > 0? ret:0;21     }22 23 24 }

 

转载于:https://www.cnblogs.com/wylwyl/p/10422709.html

你可能感兴趣的文章
Corner case
查看>>
Anagrams
查看>>
ETL开发
查看>>
POJ 1166 The Clocks (爆搜 || 高斯消元)
查看>>
如何实现一个malloc
查看>>
javascript基础 之 void
查看>>
【DRP】【SQL】-悲观锁-防止多用户同时操作时出现脏数据
查看>>
MRC
查看>>
python_day25__02__异常处理__try---exception—else---finally
查看>>
常见的HTTP错误码
查看>>
python_集合(set)
查看>>
JS --正则表达式
查看>>
归并排序(分治)
查看>>
JavaScript中的流程控制
查看>>
js处理时间戳
查看>>
MySQL进阶11--DDL数据库定义语言--库创建/修改/删除--表的创建/修改/删除/复制
查看>>
[nRF51822] 13、浅谈nRF51822和NRF24LE1/NRF24LU1/NRF24L01经典2.4G模块无线通信配置与流程...
查看>>
[模拟电路] 2、Passive Band Pass Filter
查看>>
一、SecureCRT 8.0 客户端连接服务器
查看>>
Notes for Studying Django
查看>>