• 124. 二叉树中的最大路径和


    通过递归,判断以当前节点为根的树是否为最大值,然后取当前节点单条路径的最大值给父节点调用。

     

    #include<iostream>
    #include <vector>
    #include <set>
    #include <functional>
    #include <stdlib.h>
    #include <stdio.h>
    #include <string>
    #include <sstream>
    #include <list>
    #include <map>
    #include <stack>
    #include <algorithm>
    #include<iomanip>
    
    #define INT_MIN     (-2147483647 - 1) /* minimum (signed) int value */
    #define INT_MAX       2147483647    /* maximum (signed) int value */
    
    using namespace std;
    
     struct TreeNode {
         int val;
         TreeNode *left;
         TreeNode *right;
         TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     };
    
     int maxPath = INT_MIN;
     int Max(int a, int b, int c,int d)
     {
    	 if (a<b)
    		 a = b;
    	 if (c < d)
    		 c = d;
    	 return a > c ? a : c;
     }
     int Max(int a, int b, int c)
     {
    	 if (a<b)
    		 a = b;
    	 return a > c ? a : c;
     }
     int maxPathSum2(TreeNode* root) {
    	 if (root == nullptr)
    		 return 0;
    
    	 int lMax=0, rMax = 0;
    	 if (root->left != nullptr)
    		 lMax = maxPathSum2(root->left);
    	 if (root->right != nullptr)
    		 rMax = maxPathSum2(root->right);
    
    	 int max = Max(root->val, root->val + lMax, root->val + rMax, root->val + rMax + lMax);
    	 int pathmax = Max(root->val, root->val + lMax, root->val + rMax);
    
    	 if (max > maxPath)
    		 maxPath = max;
    
    	 return pathmax > 0 ? pathmax : 0;
     }
     int maxPathSum(TreeNode* root) {
    	 if (root == nullptr)
    		 return 0;
    	 maxPathSum2(root);
    	 return maxPath;
     }
    int main(int argc, char** args)
    {
    	TreeNode root(-10);
    	root.left = new TreeNode(9);
    	root.right = new TreeNode(20);
    	root.right->left = new TreeNode(15);
    	root.right->right = new TreeNode(7);
    	cout << maxPathSum(&root) << endl;
    	system("pause");
    	return 0;
    }
    

      

  • 相关阅读:
    Myeclipse修改jdk版本流程
    web框架的前生 socket写网站
    jmeter APP接口压力测试
    BeanShell实现加密解密功能
    jmeter BeanShell的几种使用方式
    jmeter多个接口测试
    jenkins添加TPS与服务器监控变化曲线图
    Jenkins的HTML报告增加显示Throughput展示
    Jmeter 分布式部署-远程服务器的搭建与设置
    Jenkins+Jmeter配置(Linux环境)
  • 原文地址:https://www.cnblogs.com/Oscar67/p/9597282.html
Copyright © 2020-2023  润新知