您的位置:首页 > 其它

在二叉树中找到累加和为指定值的最长路径长度

2017-11-16 11:20 274 查看


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));
}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hashmap 存储 累加和
相关文章推荐