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;
        }
    };
  • 相关阅读:
    如何有效的遍历django的QuerySet
    python进程池剖析(三)
    python进程池剖析(二)
    python进程池剖析(一)
    条件变量signal与unlock的顺序
    智能指针与句柄类(四)
    解析正则 /(d)(?=(d{3})+.)/g
    原生JS实现增加删除class
    RN 热更新
    Windows下搭建IOS开发环境
  • 原文地址:https://www.cnblogs.com/x1957/p/3499550.html
Copyright © 2011-2022 走看看