首页 > 其他 > 详细

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

时间:2019-06-05 00:27:41      阅读:350      评论:0      收藏:0      [点我收藏+]

题意

给定二叉树头结点和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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!