<span style="font-size:18px;">/*************************************************************************
> File Name: Binary_Tree_Maximum_Path_Sum.cpp
> Author:
> Mail:
> Created Time: 2014年08月25日 星期一 10时41分17秒
************************************************************************/
/*************************************************************************
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
*************************************************************************/
#include<iostream>
#include<stdio.h>
using namespace std;
struct node
{
public:
node()
{
left = NULL;
right = NULL;
}
int data;
struct node *left;
struct node *right;
};
typedef struct node* Node;
Node root;
void list_create()
{
root = new struct node;
root->data = 1;
Node node1 = new struct node;
node1->data = 2;
root->left = node1;
Node node2 = new struct node;
node2->data = 3;
root->right = node2;
Node node3 = new struct node;
node3->data = 4;
node1->left = node3;
Node node4 = new struct node;
node4->data = 5;
node2->right = node4;
Node node5 = new struct node;
node5->data = 7;
node1->right = node5;
}
void solution(Node root, int &maxdeep)
{
if(root == NULL)
{
maxdeep = 0;
return;
}
int maxleft = 0;
int maxright = 0;
solution(root->left, maxleft);
solution(root->right, maxright);
if(maxleft > maxright)
{
maxdeep = maxleft + root->data;
}
else
{
maxdeep = maxright + root->data;
}
}
int main()
{
int maxdeep = 0;
list_create();
solution(root,maxdeep);
printf("maxdeep %d\n", maxdeep);
return 0;
}
</span>
Binary Tree Maximum Path Sum
最新推荐文章于 2024-03-25 21:39:45 发布