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

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

Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some

starting node to any node in the tree along the parent-child
connections. The path does not need to go through the root.

For example: Given the below binary tree,

1  / \ 2   3 Return 6.

递归解法

思路

树的问题一般都用递归的解法, 递归结束条件为节点为空返回sum为0. 因为最大值处理为 root, root+ left , root + right 这三种情况还可能是root+ left + right, 所以维护一个数组来存储第四种情况的值(java无法按引用传,就只能建立一个数组)

复杂度

时间O(n) 空间栈O(logn)

代码

public int maxPathSum(TreeNode root) {        int[] tem = new int[1];        tem[0] = Integer.MIN_VALUE;        helper(root, tem);        return tem[0];    }public int helper(TreeNode root, int[] tem) {        if (root == null) {            return 0;        }        int left = helper(root.left, tem);        int right = helper(root.right, tem);        int max = Math.max(Math.max(root.val + left, root.val + right), root.val);        tem[0] = Math.max(max, Math.max(root.val + left + right, tem[0]));        return max;    }

转载地址:http://rwqil.baihongyu.com/

你可能感兴趣的文章
POJ 1276 Cash Machine
查看>>
C语言中 struct成员变量顺序对内存的占用
查看>>
POJ1291-并查集/dfs
查看>>
移动办公首选!电商热卖轻薄本高低该怎么选?
查看>>
[译] RNN 循环神经网络系列 1:基本 RNN 与 CHAR-RNN
查看>>
Android技能树 — PopupWindow小结
查看>>
如何在create-react-app项目中使用vw实现手淘vw移动端适配布局
查看>>
Wormhole燃烧地址到底有多安全
查看>>
Web探索之旅 | 第三部分第三课:协议
查看>>
20个优秀手机界面扁平化设计,让你一秒看懂扁平化
查看>>
从百度的PPT文化看程序员晋升
查看>>
Python测试登录功能
查看>>
mysql 创建高性能索引
查看>>
babel插件入门-AST(抽象语法树)
查看>>
分布式ID
查看>>
原声写法操作table
查看>>
10 分钟内快速构建能够承载海量数据的 nginx 日志分析与报警平台
查看>>
完全二叉树实现优先队列与堆排序
查看>>
启动时间知多少?8款音视频类应用测评报告分析
查看>>
公司来了个“奇葩”的程序员
查看>>