【LeetCode】257. Binary Tree Paths 二叉樹的所有路徑(Easy)(JAVA)
阿新 • • 發佈:2020-12-09
技術標籤:Leetcode二叉樹leetcodejava資料結構演算法
【LeetCode】257. Binary Tree Paths 二叉樹的所有路徑(Easy)(JAVA)
題目地址: https://leetcode.com/problems/binary-tree-paths/
題目描述:
Given a binary tree, return all root-to-leaf paths.
Note:A leaf is a node with no children.
Example:
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
題目大意
給定一個二叉樹,返回所有從根節點到葉子節點的路徑。
說明: 葉子節點是指沒有子節點的節點。
解題方法
- 從上往下遍歷,把所有節點的值記到一個 list 中
- 遇到葉子節點(也就是沒有子節點的節點),就把 list 中轉換為指定格式
- note: 記得遍歷結束要把 list 中剛加入的元素去掉,因為另一個分支還需要使用
class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); List<Integer> list = new ArrayList<>(); bH(res, list, root); return res; } public void bH(List<String> res, List<Integer> list, TreeNode root) { if (root == null) return; list.add(root.val); if (root.left == null && root.right == null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); if (i != list.size() - 1) sb.append("->"); } res.add(sb.toString()); } else { if (root.left != null) bH(res, list, root.left); if (root.right != null) bH(res, list, root.right); } list.remove(list.size() - 1); } }
執行耗時:2 ms,擊敗了84.52% 的Java使用者
記憶體消耗:38.3 MB,擊敗了98.95% 的Java使用者