给定一棵二叉树的头节点head和一个32位整数sum,二叉树节点值类型为整型,求累加和为sum的最长路径长度。路径是指从某个节点往下,每次多选择一个孩子节点或者不选所形成的节点链。
思路:
HashMap<Integer, Integer> sumMap = new HashMap<>(); //记录累加和 和 累加和在路径中最早出现的层数
//比如说level为5时,curSum = 13,target = 5,那么就要看之前有没有和为8的出现
//发现了level为2时,累加和为8
//那么这里的max_length就可以试着更新为5-2 = 3.
//之所以这么说,是因为有个关系一直存在,target = curSum - preSum.这是我们追求的
//我们往map里加的都是preSum,所以就找curSum - target,使得追求的东西被实现
package alg;
import java.util.HashMap;
public class SumMaxLen {
//二叉树节点的定义
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
public static void main(String[]args)
{
/**
-3
3 -9
1 0 2 1
1 6
*/
Node node =new Node(-3);
node.left=new Node(3);
node.right=new Node(-9);
node.left.left=new Node(1);
node.left.right=new Node(0);
node.right.left=new Node(2);
node.right.right=new Node(1);
node.left.right.left=new Node(1);
node.left.right.right=new Node(6);
System.out.println("最长路径为:"+sumMaxLen(node,6));
System.out.println("最长路径为:"+sumMaxLen(node,-9));
}
public static int sumMaxLen(Node head, int target) {
HashMap<Integer, Integer> sumMap = new HashMap<>();
sumMap.put(0, 0);
return preOrder(head, target, 0, 1, 0, sumMap);
}
//利用二叉树前序遍历
public static int preOrder(Node head, int target, int preSum, int level, int maxLen, HashMap<Integer, Integer> sumMap) {
if (head == null) {
return maxLen;
}
//当前节点的最大值计算
int curSum = preSum + head.value;
//集合中不存在当前值
if (!sumMap.containsKey(curSum)) {
sumMap.put(curSum, level);
}
//更新最大长度
if (sumMap.containsKey(curSum - target)) {
//取两者的最大值
maxLen = Math.max(level - sumMap.get(curSum - target), maxLen);
}
//递归调用
maxLen = preOrder(head.left, target, curSum, level + 1, maxLen, sumMap);//左子树
maxLen = preOrder(head.right, target, curSum, level + 1, maxLen, sumMap);//右子树
if (level == sumMap.get(curSum)) {
sumMap.remove(curSum);
}
return maxLen;
}
}