1. 程式人生 > >LeetCode刷題筆記(樹):binary-tree-maximum-path-sum

LeetCode刷題筆記(樹):binary-tree-maximum-path-sum

題目描述

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

   1
  / \
 2   3

Return6.

給定一個二叉樹,找到最大路徑和。 路徑可以在樹中的任何節點開始和結束。 例如:給定下面的二叉樹,
1
/ \
2 3

返回6。

解題思路

遞迴的思想,先分別計算左右子樹的最大值,然後通過比較maxValue和root->val + leftMax + rightMax來確定是否更行maxValue。最後,返回當前root的值加上其左右子樹中的最大值,或者0。

C++版程式碼實現

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxValue = 0;
    int maxPathSum(TreeNode *root) {
        if(root == NULL)
            return
0; maxValue = -0x7fffff; getMaxPathSum(root); return maxValue; } int getMaxPathSum(TreeNode *root){ if(root == NULL) return 0; int leftMax = max(0, getMaxPathSum(root->left)); int rightMax = max(0, getMaxPathSum(root->right)); maxValue = max(maxValue, root->val + leftMax + rightMax); return
max(0, root->val + max(leftMax, rightMax)); } };

系列教程持續釋出中,歡迎訂閱、關注、收藏、評論、點贊哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz