0
点赞
收藏
分享

微信扫一扫

LeetCode.124. 二叉树中的最大路径和

求阙者 2022-03-27 阅读 37

LeetCode.124. 二叉树中的最大路径和

难度:hard

 

 

 递归:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int ans = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        maxGet(root);
        return ans;
    }
    public int maxGet(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int leftMax = Math.max(0, maxGet(node.left));
        int rightMax = Math.max(0, maxGet(node.right));
        ans = Math.max(ans, leftMax + rightMax + node.val);
        return Math.max(leftMax, rightMax) + node.val;
    }
}

复杂度分析:

  • 时间复杂度:O(N),遍历N个节点
  • 空间复杂度:O(N)递归调用的层数,最坏情况:二叉树的高度等于节点个数
举报

相关推荐

0 条评论