zoukankan      html  css  js  c++  java
  • [leetcode-124-Binary Tree Maximum Path Sum]

    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 must contain at least one node and does not need to go through the root.
    For example:
    Given the below binary tree,
       1
      /
      2    3
    Return 6.

    思路:

    用一个全局变量来记录最大路径和。

    对于一个结点,一旦得到他的左子树与右子树的最大路径和,那么也就能得到最终该结点的最大路径和。

    递归函数很好理解。如下:

    int maxToRoot(TreeNode* root,int &result)
        {
            if (root == NULL)return 0;
            int left = maxToRoot(root->left,result);
            int right = maxToRoot(root->right, result);
            if (left  < 0)left = 0;
            if (right < 0)right = 0;
            if (left + right + root->val > result) result = left + right + root->val;
            return root->val += max(left,right);
        }
        int maxPathSum(TreeNode* root)
        {
            int max = -2147483648;
            maxToRoot(root, max);
            return max;
        }

    参考:

    https://discuss.leetcode.com/topic/5508/simple-o-n-algorithm-with-one-traversal-through-the-tree

  • 相关阅读:
    axios
    es6
    $route监听路由变化
    容易挂
    自定义全局组件/插件
    eslintrc.js
    dev-server.js
    webpack-dev-server.js
    怎么消除间隔间的空白字符
    es6语法
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6605357.html
Copyright © 2011-2022 走看看