[剑指offer][JAVA]面试题第[34]题[二叉树中和为某一值的路径][回溯]
【問題描述】[中等]
輸入一棵二叉樹和一個整數,打印出二叉樹中節點值的和為輸入整數的所有路徑。從樹的根節點開始往下一直到葉節點所經過的節點形成一條路徑。示例: 給定如下二叉樹,以及目標和 sum = 22,5/ \4 8/ / \11 13 4/ \ / \7 2 5 1 返回:[[5,4,11,2],[5,8,4,5] ]提示:節點總數 <= 10000【解答思路】
1. 回溯
時間復雜度:O(N) 空間復雜度:O(N)
sum==target 作為出口
LinkedList<List<Integer>> res = new LinkedList<>();LinkedList<Integer> path = new LinkedList<>(); public List<List<Integer>> pathSum(TreeNode root, int sum) {recur(root, sum, 0);return res;}void recur(TreeNode root, int sum,int tar) {if(root == null) return;path.add(root.val);tar += root.val;if(tar == sum && root.left == null && root.right == null)res.add(new LinkedList(path));recur(root.left,sum, tar);recur(root.right,sum, tar);path.removeLast();//回溯}詳細注釋
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ class Solution {public List<List<Integer>> pathSum(TreeNode root, int sum) {List<List<Integer>> lists = new ArrayList<>();if(root == null) return lists;findPath(new ArrayList<Integer>(),root,sum,0,lists);return lists;}/** path:用于存放當前節點所在的路徑(隨著遍歷一直在變動)*/private static void findPath(List<Integer> path, TreeNode node, int sum, int tempSum,List<List<Integer>> lists) {//到當前節點位置的路徑的節點值的和tempSum += node.val;//path.add(node.val);if(tempSum == sum && node.left == null &&node.right == null) {//得到一個符合要求的路徑時,創建一個新的ArrayList,拷貝當前路徑到其中,并添加到lists中lists.add(new ArrayList(path));}if(node.left != null) {findPath(path,node.left,sum,tempSum,lists);//遞歸結束時,該留的路徑已經記錄了,不符合的路徑也都不用理,刪掉當前路徑節點的值path.remove(path.size()-1);}if(node.right != null) {findPath(path,node.right,sum,tempSum,lists);//遞歸結束時,該留的路徑已經記錄了,不符合的路徑也都不用理,刪掉當前路徑節點的值path.remove(path.size()-1);}} }【總結】
1.淺拷貝 深拷貝
2. res.add(new LinkedList(path))對比res.add(path)
res.add(path) 淺拷貝
res.add(new LinkedList(path)) 深拷貝
記錄路徑時若直接執行 res.append(path) ,則是將 path 列表對象 加入了 res ;后續 path 對象改變時, res 中的 path 對象 也會隨之改變(因此肯定是不對的,本來存的是正確的路徑 path ,后面又 append 又 pop 的,就破壞了這個正確路徑)。list(path) 相當于新建并復制了一個 path 列表,因此不會受到 path 變化的影響。
3.回溯記得要回溯~ 體現回溯
path.removeLast();//回溯轉載鏈接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/solution/mian-shi-ti-34-er-cha-shu-zhong-he-wei-mou-yi-zh-5/
參考鏈接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/solution/yi-kan-jiu-dong-xi-lie-by-mu-yi-wei-lan/
總結
以上是生活随笔為你收集整理的[剑指offer][JAVA]面试题第[34]题[二叉树中和为某一值的路径][回溯]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab plot颜色
- 下一篇: jsp出现错误