zoukankan      html  css  js  c++  java
  • [Leetcode] 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
    

    Return6.

     思路:题目中说明起始节点可以是任意节点,所以,最大的路径和不一样要经过root,可以是左子树中某一条,或者是右子树中某一条,当然也可能是经过树的根节点root的。递归式是应该是这三者中选出最大者。这题是看完yucoding的博客才算可能理解,这里只是用中文讲解该博客中的分析过程。举例子:

    对树中的任一节点,当有一条路径经过它时(不一定为最大),有两种情况:

    1)“顶节点”为当前节点时,如当前节点为2时,路径为6->4->2->5->-3;

    2)“顶节点”为当前节点的父节点1,当前节点为2时,路径为-3->5->2->1->-3->6

    对某个节点a,最大路径为:

    i) max_top(a)为第一种情况下的最大路径和;

    ii) max_single(a)为第二种情况下的最大路径和;

    则,max_top(a)=Max{max_single(a), max_single(a->left)+max_single(a->right)+a->val, a->val};

         max_single(a)=Max{max_single(a->left)+a->val, max_single(a->right)+a->val, a->val};

    最每个节点a,res=max(res, max_top(a))。

    其实,个人这样理解的,以当前点为“顶结点”,则,需从只有一条子树的和、两条子树加顶点的和、该顶点的值三种中选出最大值作为所求值;若以当前点的父结点为顶结点,说明这条路径必须经过该父结点,所以,求经过当前结点的路径,只能是从叶结点到当前结点(再到父结点),即只有一条而不能是两条之和,若是再求两条之后,则后续就不能通过该父结点了。

     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 maxPathSum(TreeNode *root) 
    13     {
    14         int res = root->val;
    15         maxPathSumDFS(root, res);
    16         return res;
    17     }
    18     int maxPathSumDFS(TreeNode *root, int &res) {
    19         if (!root) return 0;
    20         int left = maxPathSumDFS(root->left, res);
    21         int right = maxPathSumDFS(root->right, res);
    22         int top = root->val + (left > 0 ? left : 0) + (right > 0 ? right : 0); //第一种
    23         res = max(res, top);
    24         return max(left, right) > 0 ? max(left, right) + root->val : root->val;   //第二种  
    25     }
    26 };

    //代码来源Grandyang

  • 相关阅读:
    OpenCascade Primitives BRep-Cone
    OpenCascade Primitives BRep-Torus
    OpenCascade Primitives BRep-Cylinder
    OpenCascade Primitives BRep
    OpenCascade Primitives BRep
    Topology and Geometry in OpenCascade-Topology
    Topology and Geometry in OpenCascade-Face
    Topology and Geometry in OpenCascade-Edge
    Topology and Geometry in OpenCascade-Vertex
    PCurve
  • 原文地址:https://www.cnblogs.com/love-yh/p/6979929.html
Copyright © 2011-2022 走看看