zoukankan      html  css  js  c++  java
  • Binary Tree Maximum Path Sum

    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.

    思路:

      dfs

    我的代码:

    public class Solution {
        public int maxPathSum(TreeNode root) {
           if(root == null) return 0;
           helper(root);
           return max;
        }
        public int helper(TreeNode root)
        {
            if(root == null) return 0;
            if(root.left == null && root.right == null) 
            {
                max = Math.max(max,root.val);
                return root.val; 
            }
            int left = helper(root.left);
            int right = helper(root.right);
            int child = Math.max(left, right);
            int val = root.val;
            max = Math.max(Math.max(left+val+right, Math.max(val,child+val)), max);
            return Math.max(val, val+child);
        }
        private int max = Integer.MIN_VALUE;
    }
    View Code

    学习之处:

    • max的条件略复杂,自身 or 自身+maxchild or 自身+left+right 
    • return的条件 自身 or 自身 + maxchild
  • 相关阅读:
    Mysql密码操作
    最长公共子串(2017蓝桥杯省赛)
    一和零(leetcode)
    leetcode 235周赛
    袋子里最少数目的球(leetcode)
    第七周课后作业
    第四周jsp作业
    3.10
    3.4课堂练习
    DS博客作业05-查找批改
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4334524.html
Copyright © 2011-2022 走看看