由leetcode 437 路徑綜合III 所想到的

  • 由leetcode 437 路徑綜合III 所想到的

給定一個二叉樹,它的每個結點都存放着一個整數值。

找出路徑和等於給定數值的路徑總數。

路徑不需要從根節點開始,也不需要在葉子節點結束,但是路徑方向必須是向下的(只能從父節點到子節點)。

二叉樹不超過1000個節點,且節點數值範圍是 [-1000000,1000000] 的整數。

來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/path-sum-iii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

  • 思路:一開始是想把 其所有根結點的路徑到葉節點的路徑都找到 然後在路徑中尋找和爲sum的值 的個數。

    其實可以通過回溯法+前綴和比較優雅的解決。

    private int count, sum;
    //前綴和數組
    private int[] path = new int[1000];
    public int pathSum(TreeNode root, int sum) {
        this.count = 0;
        this.sum = sum;
        //前綴和map
        Map<Integer,Integer> map = new HashMap<>();
    	//初始化
        map.put(0,1);
        backTrack(root,0,map);
        return count;
    }

    public void backTrack(TreeNode root,int index,Map<Integer,Integer> map){
        if(root == null){
            return ;
        }

        if(index - 1 >= 0){
            path[index] = path[index-1]+root.val;

        }else{
            path[index] = root.val;
        }
        //計算個數
        count += map.getOrDefault(path[index]-sum,0);
        map.put(path[index],map.getOrDefault(path[index],0)+1);
        backTrack(root.left,index+1,map);
        backTrack(root.right,index+1,map);
        //恢復map
        map.put(path[index],map.getOrDefault(path[index],0)-1);
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章