您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在Java中實現(xiàn)一個二叉樹路徑,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
給定一個二叉樹,和 目標(biāo)值 = 5:
1 / \ 2 4 / \ 2 3
返回:
[ [1, 2, 2], [1, 4] ]
代碼如下:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root the root of binary tree * @param target an integer * @return all valid paths */ public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) { // Write your code here return dfs(root,new ArrayList<Integer>(),0,new ArrayList<List<Integer>>(),target); } public List<List<Integer>> dfs(TreeNode root,List<Integer> node, int sum, List<List<Integer>> paths,int target) { if(root==null) { return new ArrayList<List<Integer>>(); } List<List<Integer>> path=new ArrayList<List<Integer>>(); if(root.left!=null) { List<Integer> nodes=new ArrayList<Integer>(); if(node!=null) { nodes.addAll(node); } nodes.add(root.val); List<List<Integer>> temp=dfs(root.left,nodes,sum+root.val,paths,target); if(temp!=null) { path.addAll(temp); } } if(root.right!=null) { List<Integer> nodes=new ArrayList<Integer>(); if(node!=null) { nodes.addAll(node); } nodes.add(root.val); List<List<Integer>> temp=dfs(root.right,nodes,sum+root.val,paths,target); if(temp!=null) { path.addAll(temp); } } if(root.left==null&&root.right==null) { List<Integer> nodes=new ArrayList<Integer>(); if(node!=null) { nodes.addAll(node); } nodes.add(root.val); if(sum+root.val==target) { path.add(nodes); } else{ path=new ArrayList<List<Integer>>(); } } return path; } }
關(guān)于怎么在Java中實現(xiàn)一個二叉樹路徑就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。