1. 程式人生 > 其它 >【劍指offer較難部分10】二叉樹中和為某一值的路徑(java)

【劍指offer較難部分10】二叉樹中和為某一值的路徑(java)

技術標籤:劍指offer(java)資料結構二叉樹java演算法

題目描述

輸入一顆二叉樹的根節點和一個整數,按字典序打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。
在這裡插入圖片描述

分析

思路(遞迴):
1、用深度優先搜尋DFS
2、每當DFS搜尋到新節點時,都要儲存該節點。而且每當找出一條路徑之後,都將這個儲存到 list 的路徑儲存到二維pathList中
3、並且,每當DFS搜尋到子節點,發現不是路徑和時,返回上一個結點時,需要把該節點從list中移除
總結:先遍歷(中序)找葉子結點,到了葉子節點就找到一條路徑,判斷這條路徑結點值之和是否等於輸入的整數target,等於則新增進入最終的pathList。程式碼中可以用target減去結點值,若最終減去路徑上所有值等於0,就表示滿足要求。

實現程式碼如下:

import java.util.ArrayList;
//遞迴
public class Solution {
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        ArrayList<ArrayList<Integer>> pathList = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> list =
new ArrayList<Integer>(); if(root == null){ return pathList; } findPath(root, target, new ArrayList<Integer>(), pathList); return pathList; } public void findPath(TreeNode root, int target, ArrayList<Integer> cache, ArrayList<
ArrayList<Integer>> pathList ) { if (root == null) { return; } int val = root.val; int remainVal = target - val; // 當前節點進列表,cache用於存路徑(多個結點值組成路徑) cache.add(val); // 當前節點是葉子節點,並且remainVal等於0,即路徑上的值剛好等於target,該路徑為一條滿足條件的路徑 if (remainVal == 0 && (root.left == null && root.right == null)) { pathList.add(new ArrayList<>(cache)); } // 處理節點 findPath(root.left, remainVal, cache, pathList); findPath(root.right, remainVal, cache, pathList); // 回溯到上一個節點,即根據索引刪除cache中最後一個結點,返回到上一個 cache.remove(cache.size() - 1); } }

在這裡插入圖片描述