题目
给定一棵二叉树的头节点head和一个32位整数sum,二叉树节点值类型为整型,求累加和为sum的最长路径长度。路径是指从某个节点往下,每次多选择一个孩子节点或者不选所形成的节点链。
代码实现
public int getMaxLength(TreeNode head, int sum) {
HashMap<Integer, Integer> sumMap = new HashMap<>(); //记录累加和 和 累加和在路径中最早出现的层数
sumMap.put(0, 0); //累加和0不用包括任何节点就可以得到
return preOrder(head, sum, 0, 1, 0, sumMap);
}
public int preOrder(TreeNode head, int sum, 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 - sum)) {
maxLen = Math.max(level - sumMap.get(curSum - sum), maxLen);
}
maxLen = preOrder(head.left, sum, curSum, level + 1, maxLen, sumMap);
maxLen = preOrder(head.right, sum, curSum, level + 1, maxLen, sumMap);
if (level == sumMap.get(curSum)) { //从cur节点返回到父节点前,把遍历到cur节点加上的累加和记录删除
sumMap.remove(curSum);
}
return maxLen;
}