LeetCode–二叉樹的所有路徑
博客說明
文章所涉及的資料來自互聯網整理和個人總結,意在于個人學習和經驗匯總,如有什么地方侵權,請聯系本人洗掉,謝謝!
介紹
257. 二叉樹的所有路徑
題目
給定一個二叉樹,回傳所有從根節點到葉子節點的路徑,
說明: 葉子節點是指沒有子節點的節點,
示例:
輸入:
1
/ \
2 3
\
5
輸出: ["1->2->5", "1->3"]
解釋: 所有根節點到葉子節點的路徑為: 1->2->5, 1->3
思路
深度優先遍歷 DFS
代碼
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
dfs(root,"",paths);
return paths;
}
public void dfs(TreeNode root,String path,List<String> paths){
if(root != null){
StringBuffer pathSB = new StringBuffer(path);
pathSB.append(Integer.toString(root.val));
if(root.left == null && root.right == null){
paths.add(pathSB.toString());
}else{
pathSB.append("->");
dfs(root.left,pathSB.toString(),paths);
dfs(root.right,pathSB.toString(),paths);
}
}
}
}
感謝
Leetcode
以及勤勞的自己,個人博客,GitHub
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/10037.html
標籤:Java

