程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [LeetCode]Binary Tree Maximum Path Sum, 解題報告

[LeetCode]Binary Tree Maximum Path Sum, 解題報告

編輯:C++入門知識

題目

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,

vc+88rWlo6zS1Nfz19PK98K3vra6zc6qwP2jrLXDtb3X89fTyvfCt762us2+38zlJiMyMDU0MDu687rNMNf2sci9z6OsPCAwINTyt7W72DAsID4w1PK3tbvYvt/M5SYjMjA1NDA7Cjxicj4KCqOoMqOpzqrKssO0t7W72LXETUFYIHu1scewvdq14yAmIzQzOyDX89fTyvfCt762us2jrCC1scewvdq14yAmIzQzOyDT0tfTyvfCt762us19o6y2+LK7yse3tbvYeyC1scewvdq14yYjNDM71/PX08r3wre+trrNICYjNDM7INPS19PK98K3vra6zSB9o78KPGJyPgoK0vLOqtXiwO/Ct762srvE3LTm1NrW2Li0vdq146Ostv6y5sr3wre+trXEtqjS5crHw7+49r3atePWu8Tct8POytK7tM6jrMjnufu3tbvYtcTKx3sgtbHHsL3ateMmIzQzO9fz19PK98K3vra6zSAmIzQzOyDT0tfTyvfCt762us0gfaOs1PKx2Mi7tObU2sSz0rvP4LbUuPm92rXjtuC0zrfDzsq1xMfpv/ajrMq+wP22/rLmyve94bm5yOfPwqO6CjxpbWcgc3JjPQ=="http://www.2cto.com/uploadfile/Collfiles/20140511/20140511092309181.png" alt="\">
以節點2為例,返回到根節點1的值應該為2+5=7,而不是2+4+5=11,因為2只能訪問一次

AC代碼

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private static int maxValue;
    
    public static int maxPathSum(TreeNode root) {
        maxValue = root == null ? 0 : root.val;
        findPath(root);
        return maxValue;
    }
    
    public static int findPath(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int left = Math.max(findPath(root.left), 0);
        int right = Math.max(findPath(root.right), 0);
        
        maxValue = Math.max(maxValue, root.val + left + right);
        
        int current = Math.max(root.val, Math.max(root.val + left, root.val + right));
                
        return current;
    }
}





  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved