Binary Tree Maximum Path Sum

<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值