寻找树的最大路径--任意2个节点之间

思路:寻找一个树的最大路径,即任意两个节点之间经过的路径的最大值,这个值指的是所经过的点的值的和。

一个点的最大路径,可以存在四种情况。①自己+左子树②自己+右子树③自己④自己加左右子,我们只要求出这四种情况下最大的,就是我们的答案,利用树的特点递归求解。

package DSImp;

import java.util.*;

public class MaxTreeSum {
	static Scanner in = new Scanner(System.in);
	static int res = -1;
	static int solve(TreeNode root) {
		if (root == null)
			return 0;
		int left = solve(root.left);
		int right = solve(root.right);
		int temp = Math.max(left+root.val, right+root.val);//左、右最大的
		int returnmax = Math.max(root.val, temp);//左、右、自己里面最大的
		int curmax = Math.max(returnmax,left+right+root.val);//左、右、自己、左+右最大的
		res = Math.max(res, curmax);//更新最大值
		return returnmax;
	}

	static TreeNode BuildTree(int[] a, int i) {//建立完全二叉树
		int len = a.length;
		if (i >= len)
			return null;
		TreeNode root = new TreeNode(a[i]);
		root.left = BuildTree(a, 2 * i);
		root.right = BuildTree(a, 2 * i + 1);
		return root;
	}

	static void print(TreeNode head) {//先序遍历
		if (head == null)
			return;
		System.out.print(head.val + " ");
		print(head.left);
		print(head.right);
	}

	public static void main(String[] args) {
//		int[] a = { 0,1,2,3,4,5,6,7};
		int[] a = { 0,1,8,1,3,2};

		TreeNode head = BuildTree(a, 1);
		solve(head);
		System.out.println(res);
		print(head);
	}
}

class TreeNode {
	int val;
	TreeNode left, right;

	public TreeNode(int val) {
		this.val = val;
		this.left = null;
		this.right = null;
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值