zoukankan      html  css  js  c++  java
  • [leetcode]Binary Tree Maximum Path Sum

    从任意两个节点之间最大的一条路径...

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int ans;
        int search(TreeNode* root){
            if(root == nullptr) return 0;
            int left , right;
            left = INT_MIN; right = INT_MIN;
            //node
            if(root -> left == nullptr && root -> right == nullptr){
                if(root -> val > ans){
                    ans = root -> val;
                    return root -> val;
                } 
            }
            //left
            bool hasLeft = false;
            bool hasRight = false;
            if(root -> left != nullptr){
                left = search(root -> left);
                hasLeft = true;
            }
            //right
            if(root -> right != nullptr){
                right = search(root -> right);
                hasRight = true;
            }
            if(hasLeft && hasRight){
                if(left + right + root->val > ans){
                    ans = left + right + root -> val;
                }
            }
            if(hasLeft){
                if(left + root -> val > ans){
                    ans = left + root -> val;
                }
            }
            if(hasRight){
                if(right + root -> val > ans){
                    ans = right + root -> val;
                }
            }
            if(root -> val > ans) ans = root -> val;
            int res = INT_MIN;
            if(hasLeft){
                res = left + root -> val;
            }
            if(hasRight){
                res = max(res , right + root -> val);
            }
            res = max(res , root -> val);
            return res;
        }
        int maxPathSum(TreeNode *root) {
            if(root == nullptr) return 0;
            //left + right + root -> ans
            //left + root -> go on
            //right + root -> go on
            //root -> go on
            ans = INT_MIN;
            search(root);
            return ans;
        }
    };
  • 相关阅读:
    配置管理-SVN使用指南-Linux
    配置管理-SVN权限详解
    配置管理-SVN使用指南
    Unity3d之Mecanim(新版动画系统)
    Unity3d之Animation(动画系统)
    iTween基础之iTweenPath(自定义路径移动)
    iTween基础之Color(变换颜色)
    unity工具IGamesTools之批量生成帧动画
    unity2d之2d帧动画创建
    iTween基础之Fade(淡入淡出)
  • 原文地址:https://www.cnblogs.com/x1957/p/3499550.html
Copyright © 2011-2022 走看看