zoukankan      html  css  js  c++  java
  • leetcode124 二叉树中的最大路径和

    思路:

    后序遍历。

    实现:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10  * };
    11  */
    12 
    13 class Solution
    14 {
    15 public:
    16     int dfs(TreeNode* root, int& res)
    17     {
    18         int l = -1001, r = -1001;
    19         if (root->left) l = dfs(root->left, res);
    20         if (root->right) r = dfs(root->right, res);
    21         res = max(res, max(l, r));
    22         int tmp = root->val;
    23         if (l > 0) tmp += l;
    24         if (r > 0) tmp += r;
    25         res = max(res, tmp);
    26         return max(max(l, r), 0) + root->val;
    27     }
    28     int maxPathSum(TreeNode* root)
    29     {
    30         if (root == NULL) return 0;
    31         int res = -1001;
    32         dfs(root, res);
    33         return res;
    34     }
    35 };
  • 相关阅读:
    powershell查看pc信息的常用命令
    OSPF_Network-type
    redistribute and Suboptimal routing
    redistribute_prefix
    分发列表
    自增和自减
    逻辑运算
    判断闰年
    XenApp简单部署
    使用git将本地文件提交到github存储库
  • 原文地址:https://www.cnblogs.com/wangyiming/p/14693118.html
Copyright © 2011-2022 走看看