日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode OJ 113. Path Sum II

發布時間:2024/8/26 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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,

5/ \4 8/ / \11 13 4/ \ / \7 2 5 1

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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。