1. 程式人生 > >124. 二叉樹中的最大路徑和

124. 二叉樹中的最大路徑和

sig info truct tdi maximum vector root value cti

通過遞歸,判斷以當前節點為根的樹是否為最大值,然後取當前節點單條路徑的最大值給父節點調用。

技術分享圖片

#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;
}

  

124. 二叉樹中的最大路徑和