A 8-Line C# Solution

  • 0
        public int MaxPathSum(TreeNode root){
            int max = int.MinValue;
            maxSinglePath(ref max, root);
            return max;
        private int maxSinglePath(ref int maxPath, TreeNode node){
            if (node == null) return 0;
            int leftPath = Math.Max(maxSinglePath(ref maxPath, node.left), 0);
            int rightPath = Math.Max(maxSinglePath(ref maxPath, node.right), 0);
            maxPath = Math.Max(maxPath, leftPath + rightPath + node.val);
            return node.val + Math.Max(leftPath, rightPath);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.