zoukankan      html  css  js  c++  java
  • 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 does not need to go through the root.

    For example:
    Given the below binary tree,

           1
          / 
         2   3
    

     

    Return 6.

    思路:所求的maximum path sum有可能会包括一个根节点和两条分别在左右子树中的路径,这里构建一个新的树,每个节点存储的值为所给二叉树对应位置节点向下的最大单条路径(不会在根节点分叉)。然后遍历整个树,找到maximum path sum。

    代码中copyTree函数为构建树。遍历树并找到maximum path sum在help函数中实现。

     1 class Solution {
     2 public:
     3     TreeNode* copyTree(TreeNode* root)
     4     {
     5         if (!root) return NULL;
     6         TreeNode* cur = new TreeNode(root->val);
     7         cur->left = copyTree(root->left);
     8         cur->right = copyTree(root->right);
     9         int largest = 0;
    10         if (cur->left) largest = max(largest, cur->left->val);
    11         if (cur->right) largest = max(largest, cur->right->val);
    12         cur->val += largest;
    13         return cur;
    14     }
    15     void help(TreeNode* root, TreeNode* cproot, int& res)
    16     {
    17         if (!root) return;
    18         int localSum = root->val;
    19         if (cproot->left && cproot->left->val > 0)
    20             localSum += cproot->left->val;
    21         if (cproot->right && cproot->right->val > 0)
    22             localSum += cproot->right->val;
    23         if (localSum > res) res = localSum;
    24         help(root->left, cproot->left, res);
    25         help(root->right, cproot->right, res);
    26     }
    27     int maxPathSum(TreeNode* root) {
    28         TreeNode* cproot = copyTree(root);
    29         int res = INT_MIN;
    30         help(root, cproot, res);
    31         return res;
    32     }
    33 };
  • 相关阅读:
    程序调试的利器GDB
    Building a Android Development Environment
    手机的串号IMEI/ESN标示位置图解摩托罗拉官方教程
    Linux调试信息输出串口设备号的设置
    git忽略文件提交
    Spring @Transactional事务传播范围以及隔离级别
    自定义springbootstarter
    maven 命令将jar包安装到本地仓库
    oracle 常用命令
    Oracle 用户(user)和模式(schema)的区别
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5469693.html
Copyright © 2011-2022 走看看