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.

For example:

Given the below binary tree,

       1
      / \
     2   3

Return 6.

方法一 :

1. 对于每一个结点,分别遍历其左右子树,获取左子树和右子树的最大结点和:leftMax、rightMax。如果最大结点和小于0,则忽略该子树。max = leftMax + rightMax + 该结点的值。

2. 从根节点开始,遍历整棵树,并执行步骤1的操作。

	private int leftMax = Integer.MIN_VALUE;
	private int rightMax = Integer.MIN_VALUE;
	private int max = Integer.MIN_VALUE;
	public void preOrderLeft(TreeNode node , int temp) {
		if (node != null) {
			temp = temp + node.val;
			if (node.left == null && node.right == null) {
				if (leftMax < temp) {
					leftMax = temp;
				}
			}
			preOrderLeft(node.left, temp);
			preOrderLeft(node.right, temp);
			
		}
	}
	public void preOrderRight(TreeNode node , int temp) {
		if (node != null) {
			temp = temp + node.val;
			if (node.left == null && node.right == null) {
				if (rightMax < temp) {
					rightMax = temp;
				}
			}
			
			preOrderRight(node.left, temp);
			preOrderRight(node.right, temp);
		}
	}
	public void solve(TreeNode root) {
		if (root != null) {
			leftMax = Integer.MIN_VALUE;
			rightMax = Integer.MIN_VALUE;
			preOrderLeft(root.left, 0);
			preOrderRight(root.right,0);
			int tempMax = (leftMax > 0? leftMax : 0) + (rightMax > 0 ? rightMax : 0);
			if (max < tempMax + root.val) {
				max = tempMax + root.val;
			}
			solve(root.left);
			solve(root.right);
		}
	}
    public int maxPathSum(TreeNode root) {
        if (root == null) {
        	return 0;
        } else {
        	solve(root);
        	return max;
        }
    }
方法二:

       方法一对于每一个结点都需要分别递归左右子树,时间复杂度太大。

       可以考虑在遍历的同时计算出来当前最大的路径和,采用后序遍历的方法

//	int maxPS = Integer.MIN_VALUE;
//	public int maxPath(TreeNode node) {
//		if (node == null) {
//			return 0;
//		} else {
//			int max = 0;
//			if (node.left == null) {
//				int rightMax = maxPath(node.right);
//				max = rightMax >0 ? rightMax + node.val : node.val; 
//			} else if (node.right == null) {
//				int leftMax = maxPath(node.left);
//				max = leftMax > 0 ? leftMax + node.val : node.val;
//			} else {
//				int leftMax = maxPath(node.left);
//				int rightMax = maxPath(node.right);
//				if (rightMax + leftMax + node.val  > maxPS) {
//					maxPS = rightMax + leftMax + node.val;
//				}
//				int tempMax = leftMax > rightMax ? leftMax: rightMax;
//				max = tempMax > 0? node.val + tempMax : node.val;
//			}
//			if (max > maxPS) {
//				maxPS = max;
//			}
//			return max;
//		}
//	}
//	
//    public int maxPathSum(TreeNode root) {
//        if (root == null) {
//        	return 0;
//        } else {
//        	maxPath(root);
//        	return maxPS;
//        }
//    }






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值