• [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;
        }
    };
  • 相关阅读:
    NS3之路---NS3Tutorial解读---Introduction & Resource
    NS3之路---在NS3中添加openflow模块
    NS3之路---代码编辑器VIM
    2019.9.5绘图
    2019.9.4拖拽事件
    2019.9.3视频播放
    2019.08.30数组去重的几种方法以及所需时间对比
    2019.08.29定时器以及轮播图
    2019.08.27BOM的六个子对象(2)
    2019.08.27BOM的六个子对象(1)
  • 原文地址:https://www.cnblogs.com/x1957/p/3499550.html
Copyright © 2020-2023  润新知