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;
    };
  • 相关阅读:
    调用google地图
    jQuery放大镜效果
    jQuery拖到效果
    jQuery制作相册
    jQuery ui插件用法
    jQuery写fadeTo方法
    jQuery实现动画效果
    jQuery的slideToggle方法
    控经纬度显示地图与卫星
    像百度那样的智能感知效果
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854355.html
Copyright © 2011-2022 走看看