zoukankan      html  css  js  c++  java
  • 面试题10:二叉树的最大路径和

    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.

     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         int maxVal = INT_MIN;
    14         maxPathSum(root,maxVal);
    15         return maxVal;
    16     }
    17     int maxPathSum(TreeNode *root,int& maxVal) {
    18         if(root == nullptr) return 0;
    19         int leftRes = max(0,maxPathSum(root->left,maxVal));
    20         int rightRes = max(0,maxPathSum(root->right,maxVal));
    21         maxVal = max(maxVal,leftRes + rightRes + root->val);
    22         return max(leftRes,rightRes) + root->val;
    23     }
    24 };
  • 相关阅读:
    MySQL Binlog解析(2)
    在线修改GTID模式
    官方online ddl
    pt-osc原理
    pt-osc使用方法
    python基本数据类型
    第一句python
    搭建私有云kodexplorer
    frp搭建
    Linux下快速分析DUMP文件
  • 原文地址:https://www.cnblogs.com/wxquare/p/6852317.html
Copyright © 2011-2022 走看看