美文网首页算法
【算法】二叉树中的最大路径和

【算法】二叉树中的最大路径和

作者: 宋唐不送糖 | 来源:发表于2019-11-13 10:58 被阅读0次

    二叉树中的最大路径和

    描述

    给定一个非空二叉树,返回其最大路径和。

    输入: [-10,9,20,null,null,15,7]
    
       -10
       / \
      9  20
        /  \
       15   7
    
    输出: 42
    

    解题思路

    1、对每一个节点都计算出有穿过它但不穿过父节点的最大路径和。
    2、整体最大路径就是所有节点结果的最大值。

    //最小整数值
        private int sum = Integer.MIN_VALUE;
        
        //求出经过某个节点的最大路径值
        private int nodeValue(TreeNode node)
        {
            if (node == null) return 0;
            
            //后序遍历树
            int leftValue = Math.max(nodeValue(node.left), 0);
            int rightValue = Math.max(nodeValue(node.right), 0);
            //比较经过该点左右节点路径的值
            sum = Math.max(sum, node.val + leftValue + rightValue);
            return node.val + Math.max(leftValue, rightValue);
        }
        
            // 时间、空间复杂度:O(n)
        public int maxPathSum(TreeNode root)
        {
            return Math.max(this.nodeValue(root), sum);
        }
    

    相关文章

      网友评论

        本文标题:【算法】二叉树中的最大路径和

        本文链接:https://www.haomeiwen.com/subject/tukhictx.html