zoukankan      html  css  js  c++  java
  • LeetCode 124 Binary Tree Maximum Path Sum

    题目链接:

    https://leetcode.com/problems/binary-tree-maximum-path-sum/description/

    Given a non-empty 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.

    Example 1:

    
    
    
    

    Example 2:

    
    

     
     
    dfs 深度遍历
    遍历的时候,记录根节点到左子树和右子树中的某个点的最大距离,再比较下即可
    class Solution {
    public:
        int ans = -99999999;
        int maxPathSum(TreeNode* root) {
          
            dfs(root);
            return ans;
        }
        
        int dfs(TreeNode* root)
        {
            if(root->left==NULL&&root->right==NULL)
            {  ans=max(ans,root->val);return root->val;}
            if(root->left!=NULL&&root->right==NULL)
            {
                int xleft = dfs(root->left);
                ans = max(ans,max(root->val+xleft,root->val));
                return max(root->val+xleft,root->val);
            }
            if(root->left==NULL&&root->right!=NULL)
            {
                int xright = dfs(root->right);
                ans = max(ans,max(root->val,root->val+xright));
                return max(root->val,root->val+xright);
            }
            if(root->left!=NULL&&root->right!=NULL)
            {
                int xleft = dfs(root->left);
                int xright = dfs(root->right);
                ans = max(ans,max(root->val,max(root->val+xleft,max(root->val+xleft+xright,root->val+xright))));
                return max(root->val,max(root->val+xleft,root->val+xright));
            }
        }
        
        
    };
  • 相关阅读:
    DOM getElementById
    百度之星2014
    游艇租借
    2014年acm亚洲区域赛·鞍山站
    UVALive 4255 Guess
    UVA 10054 The Necklace
    UVA 10047 The Monocycle
    UVA 11624 Fire!
    第九届黑龙江省赛
    剑指offer系列31-----二叉树的下一个节点
  • 原文地址:https://www.cnblogs.com/dacc123/p/9347046.html
Copyright © 2011-2022 走看看