leetcode113. 路径总和 II(dfs)
生活随笔
收集整理的這篇文章主要介紹了
leetcode113. 路径总和 II(dfs)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個二叉樹和一個目標和,找到所有從根節點到葉子節點路徑總和等于給定目標和的路徑。說明: 葉子節點是指沒有子節點的節點。示例:
給定如下二叉樹,以及目標和 sum = 22,5/ \4 8/ / \11 13 4/ \ / \7 2 5 1
返回:[[5,4,11,2],[5,8,4,5]
]
代碼
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ class Solution {int tar;List<List<Integer>> h=new LinkedList<>();public List<List<Integer>> pathSum(TreeNode root, int sum) {tar=sum;Sum(root,0,new LinkedList<>());return h;}public void Sum(TreeNode root, int sum,LinkedList<Integer> res) {if(root==null) return;res.add(root.val);//將當前節點加入路徑if(root.left==null&&root.right==null&&sum+root.val==tar)//滿足的結果{h.add(new LinkedList<>(res));res.removeLast();return;}Sum(root.left, sum+root.val, res);Sum(root.right,sum+root.val,res);res.removeLast();//回溯} }總結
以上是生活随笔為你收集整理的leetcode113. 路径总和 II(dfs)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到朋友怎么发朋友圈
- 下一篇: 为什么做梦会梦到不认识的人