[程序员代码面试指南]二叉树问题-在二叉树中找到累加和为指定值的最长路径长度

题意

给定二叉树头结点和targetSum,打印等于targetSum的最长路径长度。

题解

是数组和等于给定值的最长子串长度的二叉树版,思想相同。
在前序遍历的过程中,找到从根节点到当前节点的满足题意的最长长度maxLen。最后得到所有节点对应的maxLen的最大长度。

代码

import java.util.HashMap;

public class Main {
	public static void main(String args[]) {
		//test
		Node root=new Node(1);
		Node n1=new Node(-1);
		Node n2=new Node(2);
		Node n3=new Node(-3);
		root.left=n1;
		root.right=n2;
		n2.left=n3;
		int targetVal=0;
		
		HashMap<Integer,Integer> sumMap=new HashMap<>();
		sumMap.put(0, 0);
		int maxLen=preOrder(root,targetVal,1,0,0,sumMap);
		System.out.println(maxLen);
	}
	
	public static int preOrder(Node root,int targetVal,int level,int preSum,int maxLen,HashMap<Integer,Integer> sumMap) {
		if(root==null) {
			return maxLen;
		}
		int curSum=preSum+root.val;//累加和
		if(!sumMap.containsKey(curSum)) {//更新HashMap
			sumMap.put(curSum, level);
		}
		if(sumMap.containsKey(curSum-targetVal)) {//更新MaxLen
			maxLen=Math.max(maxLen, level-sumMap.get(curSum-targetVal));
		}
		maxLen=preOrder(root.left,targetVal,level+1,curSum,maxLen,sumMap);
		maxLen=preOrder(root.right,targetVal,level+1,curSum,maxLen,sumMap);
		if(sumMap.get(curSum)==level) {
			sumMap.remove(curSum);
		}
		return maxLen;
	}
}
原文地址:https://www.cnblogs.com/coding-gaga/p/10976685.html