257-Binary Tree Paths
Description
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf p
All root-to-leaf paths are:
["1->2->5", "1->3"]
問題描述
給定二叉樹嗎, 返回所有根節點到葉子節點的路徑
問題分析
先序遍歷, 儲存臨時變數path, 記錄路徑, 當前節點為葉子節點時將path新增入res中即可
解法
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList();
if(root == null) return res;
dfs(root, res, "");
return res;
}
public void dfs(TreeNode root, List<String> res, String path){
if(root == null) return;
if(root.left == null && root.right == null) res.add(path + root.val);
dfs(root.left, res, path + root.val + "->");
dfs(root.right, res, path + root.val + "->");
}
}
相關文章
- Leetcode Binary Tree PathsLeetCode
- 257. Binary Tree Paths
- CF741D Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths 樹上啟發式合併(DSU ON TREE)
- Paths和Files
- find: paths must precede expression:Express
- swagger ui remove springboot pathsSwaggerUIREMSpring Boot
- Redundant Paths(POJ-3177)
- iOS資料結構與演算法實戰 二叉樹的演算法實戰 Binary Tree PathsiOS資料結構演算法二叉樹
- Java NIO 的 Files Path 和 PathsJava
- LeetCode Unique Paths(062)解法總結LeetCode
- java 檔案的操作(Path、Paths、Files)Java
- LeetCode之All Paths From Source to Target(Kotlin)LeetCodeKotlin
- tree
- Though Our Paths May Diverge(JSOI 2024 遊記)JS
- [ABC211D] Number of Shortest paths 題解
- Setup had an error Error: At least one of these paths should existErrorAST
- 【論文筆記】Shortest Paths and Centrality in Uncertain Networks筆記AI
- Angular tsconfig.json 檔案裡的 paths 用途AngularJSON
- Mac下的paths.d目錄神奇用法Mac
- DSU on Tree
- Rebuild TreeRebuild
- 01 Tree
- Tree Compass
- A - Distance in Tree
- Decision Tree
- 【MySQL(1)| B-tree和B+tree】MySql
- 多路查詢樹:B-tree/b+tree
- LeetCode#110.Balanced Binary Tree(Tree/Height/DFS/Recursion)LeetCode
- segment tree beats
- Circular Spanning Tree
- B-tree
- B+tree
- tree-shaking
- Walking the File Tree
- Root of AVL Tree
- Tree – Information TheoryORM
- mvn dependency:tree
- Traversals of binary tree