zoukankan      html  css  js  c++  java
  • 124. Binary Tree Maximum Path Sum (Tree; DFS)

    Given a 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 does not need to go through the root.

    For example:
    Given the below binary tree,

           1
          / 
         2   3
    

    Return 6.

    思路:存在val小于零的情况,所以path不一定是从叶子节点到叶子节点;每个节点存储以它为跟节点、和最大的路径,这个值依赖于左右子树=>后序遍历

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int maxPathSum(TreeNode* root) {
            maxPath = INT_MIN;
            postOrderTraverse(root);
            return maxPath;
        }
        
        int postOrderTraverse(TreeNode* root){ 
            if(root==NULL) return 0;
            int left, right, sum;
            left = postOrderTraverse(root->left);
            right = postOrderTraverse(root->right);
            left = max(left,0); //ignore negative value
            right = max(right,0);
            sum = left + right +root->val;
            if(sum > maxPath) maxPath = sum;
            return root->val+max(left,right);//return current maximum sum from one child branch to root
        }
    private: 
        int maxPath;
    };
  • 相关阅读:
    3月16日
    11月8日
    Code4 APP
    为什么alertView弹出后button会消失的问题
    设置某个类使用或者禁用ARC
    Bundle使用&NSBundle
    respondsToSelector
    NSDate获取当前时区的时间
    iOS enum 定义与使用
    IOS开发之纯代码界面--基本控件使用篇 ┊
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854355.html
Copyright © 2011-2022 走看看