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;
            
          
        }
    };
  • 相关阅读:
    Ionic 2.0 相关资料
    Tkinter的Menubutton组件
    Tkinter的Menubutton组件之OptionMenu
    Tkinter的Menu组件
    Tkinter的Scale组件
    Tkinter的Scrollbar组件
    Tkinter的Listbox组件
    Tkinter的Text组件
    Tkinter的Spinbox组件
    Tkinter的Label组件
  • 原文地址:https://www.cnblogs.com/willwu/p/6364788.html
Copyright © 2011-2022 走看看