二叉树中的最大路径和
来源:互联网 发布:键盘美化软件下载 编辑:程序博客网 时间:2024/05/01 08:11
给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)
样例
给出一棵二叉树:
1 / \ 2 3
返回 6
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /** * @param root: The root of binary tree. * @return: An integer */ int maxPathSum(TreeNode *root) { // write your code here if (root == NULL) { return 0; } int result = INT_MIN; visit(root, result); return result; }private: int visit(TreeNode *root, int &result) { if (root == NULL) { return 0; } int left = visit(root->left, result); int right = visit(root->right, result); int temp = max(left+right, max(left, right)); temp = max(root->val, temp + root->val); if (temp > result) { result = temp; } int maxBranch = max(left, right) + root->val; return max(maxBranch, root->val); }};
0 0
- LintCode-二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- 题目:二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- lintcode,二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和
- 二叉树中的最大路径和-LintCode
- LintCode 二叉树中的最大路径和
- lintcode--二叉树中的最大路径和
- 二叉树中的最大路径和-LintCode
- 二叉树中的最大路径和
- 二叉树最大路径和
- 二叉树最大路径和
- 二叉树最大路径和
- lintcode-二叉树中的最大路径和-94
- iOS UI初级-iphone开发入门
- 【备忘】java中File类的getXxx(路径相关方法)返回值
- xcode文件找不到---“AFNetworking.h”file not found
- ListView中的Item点击事件和子控件的冲突或者item点击没有反应的解决办法
- android 源码各版本下载 原生纯净版
- 二叉树中的最大路径和
- iOS UI初级-UIVew与UIWindow
- git 常用命令
- Linux命令中的rmdir
- Rectangle Area
- iOS UI初级-常用UI控件
- iOS开发中的小技巧
- linux下mysql默认安装目录和常用命令
- git 克隆远程仓库并创建分支、提交分支、获取分支