zoukankan      html  css  js  c++  java
  • Binary Tree Maximum Path Sum

    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.

    算法:(有点动态规划的思想)首先明确要自底向上进行计算,只考虑当前节点root,我们从子节点向上返回的是一条线路目前的最大值,该线路最高层(最上面)的节点是该子节点,并且该子节点不能同时有左右分支(即在线路上不能同时有左右分支,如果有分支,root返回到上一节点后,不能形成一个链,会在root出现分叉),然后我们比较root->val,

    root->val+leftMax(从左子树返回的值),root->val+rightMax(从右子树返回的值),其中最大的就是root节点应该向上返回的值,我们在计算root节点的返回值时,可以顺便计算以root为最高层节点的链的线路最大值(可以有分叉),只要比较,root->val,  leftMax+root->val,  root->val+rightMax,   leftMax+rightMax+root->val,其中最大的就是以root为最高层次节点的线路的最大值,然后用这个最大值,和最初保存的最大值result(初始化为INT_MIN)做比较,如果大于result,更新result,最终result就是结果,代码如下,时间复杂度O(n),只需要遍历一边二叉树(后序遍历):

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int  result; 
    13     int maxPathSum(TreeNode *root) {
    14         result=INT_MIN;
    15         getMax(root);
    16         return result;
    17     }
    18     int getMax(TreeNode* root)
    19     {
    20         if(root==NULL)  return 0;
    21         int leftMax=getMax(root->left);
    22         int rightMax=getMax(root->right);
    23         int tmax=max(max(leftMax+root->val,max(rightMax+root->val,root->val)),leftMax+rightMax+root->val);
    24         if(tmax>result)  result=tmax;
    25         int rootmax=max(root->val,max(root->val+leftMax,root->val+rightMax));
    26         return rootmax;
    27     }
    28 };
  • 相关阅读:
    SublimeText3下的Python开发环境配置
    从Evernote迁移到Wiz
    读书笔记---《即学即用财务常识120例》
    MC700 安装双系统
    Python3.5 + django1.8.5 安装”import pymysql pymysql.install_as_MySQLdb()”的解决方法
    7z压缩文件时排除指定的文件
    安装.NET Framework后程序无法启动的错误处理
    重拾Blog
    X240s安装Win7 以及如何启用ExpressCache
    新玩具---Amazon Kindle PaperWhite 2
  • 原文地址:https://www.cnblogs.com/sqxw/p/4007418.html
Copyright © 2011-2022 走看看