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));
            }
        }
        
        
    };
  • 相关阅读:
    JS-常用的数据结构之线性表
    Django 数据库增删改查
    Django 静态文件配置及request初识
    Django 基础
    jQuery
    前端之BOM和DOM
    前端js
    前端 css
    前端基础 html
    进度条
  • 原文地址:https://www.cnblogs.com/dacc123/p/9347046.html
Copyright © 2011-2022 走看看