1. 程式人生 > >求二叉樹的最大路徑和

求二叉樹的最大路徑和

這裡寫圖片描述

//二叉樹節點的定義
class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }

public class Solution {

    //方法一:遞迴解法,時間複雜度過高
    public int maxPathSum2(TreeNode root) {
      if(root==null)
        return 0;

      int count=Math.max(maxPathSum(root.left),maxPathSum(root.right));
      int
tem=Math.max(count,count+root.val); return Math.max(tem,maxPathSum(root.left)+maxPathSum(root.right)+root.val); } int maxValue; public int maxPathSum(TreeNode root) { maxValue=Integer.MIN_VALUE; maxPath(root); return maxValue; } //方法二:遞迴解法的優化 public
int maxPath(TreeNode node) { if(node==null) return 0; int left=Math.max(0,maxPath(node.left)); int right=Math.max(0,maxPath(node.right)); maxValue=Math.max(maxValue,left+right+node.val); return Math.max(left,right)+node.val; } public static void main(String[]args){ // System.out.println("Hello");
TreeNode root=new TreeNode(-1); root.left=new TreeNode(2); root.right=new TreeNode(3); root.left.left=new TreeNode(4); Solution s=new Solution(); System.out.println(s.maxPathSum(root)); } }