Java二叉樹路徑和代碼示例
給定一個二叉樹,找出所有路徑中各節(jié)點相加總和等于給定 目標值 的路徑。
一個有效的路徑,指的是從根節(jié)點到葉節(jié)點的路徑。
樣例
給定一個二叉樹,和 目標值 = 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; } }
referance
總結(jié)
以上就是本文關(guān)于Java二叉樹路徑和代碼示例的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
- java棧實現(xiàn)二叉樹的非遞歸遍歷的示例代碼
- Java二叉樹的四種遍歷(遞歸和非遞歸)
- JAVA二叉樹的幾種遍歷(遞歸,非遞歸)實現(xiàn)
- java二叉樹的幾種遍歷遞歸與非遞歸實現(xiàn)代碼
- java二叉樹的非遞歸遍歷
- java 對稱二叉樹的判斷
- Java 最優(yōu)二叉樹的哈夫曼算法的簡單實現(xiàn)
- Java實現(xiàn)二叉樹的建立、計算高度與遞歸輸出操作示例
- java編程題之從上往下打印出二叉樹
- java實現(xiàn)按層遍歷二叉樹
- java實現(xiàn)二叉樹遍歷的三種方式
- Java二叉樹的遍歷思想及核心代碼實現(xiàn)
- Java實現(xiàn)二叉樹的深度優(yōu)先遍歷和廣度優(yōu)先遍歷算法示例
- Java實現(xiàn)打印二叉樹所有路徑的方法
- Java實現(xiàn)的二叉樹常用操作【前序建樹,前中后遞歸非遞歸遍歷及層序遍歷】
- Java中二叉樹的建立和各種遍歷實例代碼
- java編程求二叉樹最大路徑問題代碼分析
- Java源碼解析之平衡二叉樹
相關(guān)文章
Spring?JPA使用CriteriaBuilder動態(tài)構(gòu)造查詢方式
這篇文章主要介紹了Spring?JPA使用CriteriaBuilder動態(tài)構(gòu)造查詢方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12windows系統(tǒng)使用mvn命令打包并指定jdk路徑方式
這篇文章主要介紹了windows系統(tǒng)使用mvn命令打包并指定jdk路徑方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04springboot項目mysql-connector-java默認版本如何查看
這篇文章主要介紹了springboot項目mysql-connector-java默認版本如何查看問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11Java實現(xiàn)基于UDP協(xié)議的網(wǎng)絡(luò)通信UDP編程
在Java中使用UDP編程,仍然需要使用Socket,因為應(yīng)用程序在使用UDP時必須指定網(wǎng)絡(luò)接口(IP地址)和端口號。注意:UDP端口和TCP端口雖然都使用0~65535,但他們是兩套獨立的端口,即一個應(yīng)用程序用TCP占用了端口1234,不影響另一個應(yīng)用程序用UDP占用端口12342023-04-04