Advertisement
CR7CR7

BT-MaximumPathSum

Aug 14th, 2023
856
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.83 KB | None | 0 0
  1. class Solution {
  2.     public int maxPathSum(TreeNode root) {
  3.         Stack<TreeNode> stack = new Stack<>();
  4.         int maxSum = Integer.MIN_VALUE;
  5.  
  6.         if (root != null) {
  7.             stack.push(root);
  8.         }
  9.  
  10.         while (!stack.isEmpty()) {
  11.             TreeNode node = stack.pop();
  12.  
  13.             if (node != null) {
  14.                 int currentSum = node.val;
  15.  
  16.                 if (node.left != null) {
  17.                     currentSum += Math.max(node.left.val, 0);
  18.                     stack.push(node.left);
  19.                 }
  20.  
  21.                 if (node.right != null) {
  22.                     currentSum += Math.max(node.right.val, 0);
  23.                     stack.push(node.right);
  24.                 }
  25.  
  26.                 maxSum = Math.max(maxSum, currentSum);
  27.             }
  28.         }
  29.  
  30.         return maxSum;
  31.     }
  32. }
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement