import java.util.*;
//在二叉树中找到累加和为指定值的最长路径长度
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 int sumMaxLen(Node head,int sum)
{ //存储当前节点最长路径值和所在的层数
HashMap<Integer,Integer>sumMap=new HashMap<Integer,Integer>();
sumMap.put(0,0);//没有遍历节点
return preOrder(head,sum,0,1,0,sumMap);
}
//利用二叉树前序遍历
public static int preOrder(Node 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))
{
sumMap.remove(curSum);
}
return maxLen;
}
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));
}
}
在二叉树中找到累加和为指定值的最长路径长度
最新推荐文章于 2022-06-25 18:11:51 发布