LeetCode OJ 113. Path Sum II
生活随笔
收集整理的這篇文章主要介紹了
LeetCode OJ 113. Path Sum II
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and?sum = 22,
return
[[5,4,11,2],[5,8,4,5] ]?
相比較判斷一個樹中是否有sum為某一值的從根節點到葉子節點的路徑,這個題目要求把所有這樣的路徑找出來。如果我們要用遞歸的方法,如何來存儲這樣的路徑呢?
一個節點如果有左右兩個子節點,那么就會產生兩條不同的路徑,在遞歸的過程中,我們要不斷地new一個list來存儲新出現的分支,并要把從根節點到達當前節點的路徑拷貝到新建的list中。當到達葉子節點后,如果是一條匹配路徑,則把該路徑加入到存儲路徑的list中,否則的話舍棄該路徑。代碼如下:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 12 public List<List<Integer>> list = new ArrayList(); 13 public List<List<Integer>> pathSum(TreeNode root, int sum) { 14 if(root == null) return list; 15 16 List<Integer> llist = new ArrayList(); 17 path(root, sum, llist); 18 return list; 19 } 20 21 public void path(TreeNode root, int sum, List<Integer> llist){ 22 if(root.left==null && root.right==null){ 23 if(root.val==sum){ 24 llist.add(sum); 25 list.add(llist); 26 } 27 return; 28 } 29 if(root.right!=null){ 30 List<Integer> rlist = new ArrayList(); 31 for(Integer i : llist){ 32 rlist.add(i); 33 } 34 rlist.add(root.val); 35 path(root.right, sum - root.val, rlist); 36 } 37 if(root.left!=null){ 38 llist.add(root.val); 39 path(root.left, sum - root.val, llist); 40 } 41 } 42 }?
轉載于:https://www.cnblogs.com/liujinhong/p/5455368.html
總結
以上是生活随笔為你收集整理的LeetCode OJ 113. Path Sum II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 6_2 铁轨(UVa514)栈
- 下一篇: Mysql安装过程