zoukankan      html  css  js  c++  java
  • Binary Tree Maximum Path Sumn

    Given a binary tree, find the maximum path sum.

    For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

    For example:
    Given the below binary tree,

           1
          / 
         2   3

    Return 6.

    分析: 这道题目采用后序遍历,但需要注意每个点都有能作为路径的“中点”,也有可能只是路径中一个普通的节点。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
        int res =-32768;
    public:
        int postorder(TreeNode* root){
            int leftsum =0,rightsum =0;
            if(root->left){
               leftsum =postorder(root->left);
            }
            if(root->right){
                rightsum = postorder(root->right);
            }
            int sum = root->val+ max(0,leftsum)+max(0,rightsum);
            res =  max(sum,res);
            sum =root->val+ max(max(0,leftsum),max(0,rightsum));
            res =  max(sum,res);
            return sum;
        }
        int maxPathSum(TreeNode* root) {
            postorder(root);
            return res;
            
          
        }
    };
  • 相关阅读:
    细菌 状态压缩
    素数
    骑士问题(knight)
    魔法石的诱惑
    平面上的最接近点对
    救援行动(save)
    优先队列
    leetcode 92. 反转链表 II
    leetcode 91. 解码方法
    leetcode 39. 组合总和
  • 原文地址:https://www.cnblogs.com/willwu/p/6364788.html
Copyright © 2011-2022 走看看