劍指offer二十四之二叉樹中和為某一值的路徑
阿新 • • 發佈:2017-10-07
rgs one main java http ring dal offer for
一、題目
輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。
二、思路
詳見代碼
三、代碼
1、解答代碼
import java.util.ArrayList; public class Solution { public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) { ArrayList<ArrayList<Integer>> paths = newView CodeArrayList<ArrayList<Integer>>(); if (root == null) return paths; find(paths, new ArrayList<Integer>(), root, target); return paths; } public void find(ArrayList<ArrayList<Integer>> paths, ArrayList<Integer> path, TreeNode root, inttarget) { path.add(root.val); if (root.left == null && root.right == null) { if (target == root.val) { paths.add(path); } return; } //存儲右節點的路徑 ArrayList<Integer> path2 = new ArrayList<>(); path2.addAll(path);if (root.left != null) find(paths, path, root.left, target - root.val); if (root.right != null) find(paths, path2, root.right, target - root.val); } }
2、節點類
public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } public TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }View Code
3、測試代碼
import java.util.ArrayList; public class TestMain { public static void main(String[] args) { //建立二叉樹,註意必須逆序建立,先建立子節點,再逆序往上建立,因為非葉子結點會使用到下面的節點,而初始化是按順序初始化的,不逆序建立會報錯 TreeNode G = new TreeNode(3, null, null); TreeNode F = new TreeNode(6, null, null); TreeNode E = new TreeNode(5, null, null); TreeNode D = new TreeNode(4, null, null); TreeNode C = new TreeNode(3, F, G); TreeNode B = new TreeNode(2, D, E); TreeNode A = new TreeNode(1, B, C); //調用方法 Solution solution = new Solution(); ArrayList<ArrayList<Integer>> paths = solution.FindPath(A,7); /*輸出所有路徑 1 2 4 1 3 3 */ for (ArrayList<Integer> s : paths) { for (int i = 0; i < s.size(); i++) { System.out.print(s.get(i) + " "); } System.out.println(); } } }View Code
-----------------------------------------------------------------------
參考鏈接:https://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca
劍指offer二十四之二叉樹中和為某一值的路徑